Java Reference
In-Depth Information
Display 4.1
A Simple Class
This class definition goes in a file named
DateFirstTry.java.
1
public class
DateFirstTry
2 {
3
public
String month;
4
public int
day;
5
public int
year;
//a four digit number.
Later in this chapter, we will
see that these three
public
modifiers should be replaced
with
private
.
6
public void
writeOutput()
7 {
8 System.out.println(month + " " + day + ", " + year);
9 }
10 }
This class definition (program) goes in a file named
DateFirstTryDemo.java.
1
public class
DateFirstTryDemo
2 {
3
public static void
main(String[] args)
4 {
5 DateFirstTry date1, date2;
6 date1 = new DateFirstTry();
7 date2 = new DateFirstTry();
8 date1.month = "December";
9 date1.day = 31;
10 date1.year = 2012;
11 System.out.println("date1:");
12 date1.writeOutput();
13 date2.month = "July";
14 date2.day = 4;
15 date2.year = 1776;
16 System.out.println("date2:");
17 date2.writeOutput();
18 }
19 }
Sample Dialogue
date1:
December 31, 2012
date2:
July 4, 1776
We will discuss this kind of statement in more detail later in this chapter when we
discuss something called a
constructor
. For now simply note that
Class_Variable
=
new
Class_Name
( );