Java Reference
In-Depth Information
String Lastname;
String Firstname;
int Company;
double [ ] Marks;
...
}
5.2.1 Constructor and object creation
To use an object, we first need to create it by instantiating the various fields
of the class by a special method called the constructor . We build an object
using the new keyword that will call the constructor method of the class. A
constructor is an object method bearing the class name. A constructor as all
other object methods is a non-static function. To access a record of an object
inside the current object, we use the keyword this .Thus this.field will
return the value of the field variable of the current object. The program
below shows how to define a class Date with its constructor:
Program 5.1 A class for storing dates with a constructor method
class Date
int dd ;
int mm ;
int yyyy ;
// Constructor
Date( int day , int month , int year)
{ this .dd=day;
this .mm=month ;
this . yyyy=year ; }
}
An object day of type Date is created by the following instruction:
Date day=new Date(23,12,1971);
The various records of that date object are accessed by day.dd , day.mm and
day.yyyy . The program below shows how to put altogether the newly created
class Date for encapsulating a date with the class program that creates an
object of this type and displays its various records:
Program 5.2 A small demonstration program using the Date class
class Date
int dd ;
int mm ;
int yyyy ;
 
Search WWH ::




Custom Search