public class Date{
private int day, month, year;
...
...
}
day
, month
, year
: Instance variables → In this code, set as private. Usually it is private since making it public breaks encapsulation.new
creates a new object
How to set instance variables (Since they are private → cannot be accessed by the object of a class directly)
Initializing objects
A later constructor can call an earlier one using this.
public class Date{
private int day,month, year;
public Date(int d, int m, int y){
day = d;
month = m;
year = y;
}
public Date(int d, int m){
this(d,m,2021); // Usage
}
}
If NO constructor is defined Java provides a default constructor with empty arguments.
Create a new object from an existing one.
public class Date{
private int day, month, year;
public Date(Date d){
//Note that the private instance variables of argument are visible.
this.day = d.day;
this.moth = d.month;
this.year = d.year;
}
}
public void UseDate() {
Date d1,d2;
d1 = new Date(12,4,1954);
d2 = new Date(d1);