Java Reference
In-Depth Information
Display 4.13 A Class with Constructors (part 1 of 5)
This is our final definition of a class
whose objects are dates.
1
import java.util.Scanner;
2 public class Date
3{
4
private String month;
5
private int day;
6
private int year; //a four digit number.
7
public Date()
No-argument constructor
8
{
9
month = "January";
10
day = 1;
11
year = 1000;
12
}
13
public Date( int monthInt, int day, int year)
14
{
You can invoke another
method inside a
constructor definition.
15
setDate (monthInt, day, year);
16
}
17
public Date(String monthString, int day, int year)
18
{
19
setDate (monthString, day, year);
20
}
21
public Date( int year)
22
{
A constructor usually initializes all
instance variables, even if there is not a
corresponding parameter.
23
setDate (1, 1, year);
24
}
25
public Date(Date aDate)
26
{
27
if (aDate == null )//Not a real date.
We will have more to
say about this
constructor in
Chapter 5. Although
you have had enough
material to use this
constructor, you need
not worry about it
until Section 5.3 of
Chapter 5.
28
{
29
System.out.println("Fatal Error.");
30
System.exit(0);
31
}
32
month = aDate.month;
33
day = aDate.day;
34
year = aDate.year;
35
}
(continued)
 
Search WWH ::




Custom Search