Java Reference
In-Depth Information
// Constructor (method)
Date(
int
day ,
int
month ,
int
year)
this
.dd=day;
this
.mm=month ;
this
. yyyy=year ;
}
}
class
DemoDate
{
public static void
main( String [ ]
args )
{
Date day=
new
Date(23 ,12 ,1971) ;
System . out . println (
"Date:"
+day . dd+
"/"
+day .mm+
"/"
+day . yyyy) ;
}
}
A class may potentially supply
several constructors
provided that they all bear
different signatures. For now, it is best to define a single constructor that
initializes all the fields of the object. Fields of the current object are accessed
by using the keyword
this
. Although it is not mandatory to use it explicitly
inside the constructor, we recommend initializing the object records in the
constructor by using
this
:
Date(int day, int month, int year)
{this.dd=day;
this.mm=month;
yyyy=year; // we omitted the keyword this here
}
Note that in cases where no constructor is provided, Java will use a default
constructor common to all objects. Fields can still be assigned after the object
creation as follows:
Date day=new Date();// default constructor called
day.yyyy=1971;
...
We can visualize the object creation and its relationship as depicted in
Figure 5.1.
5.2.2 The common
null
object
Similar to arrays, we can first define object variables and create/initialize them
later. For example, consider the following code:
Date day;
...// do some instructions here
Date day=new Date(23,12,1971);
Search WWH ::
Custom Search