An
interesting feature of the constructor is that a class can have multiple
constructors. This is called Constructor
Overloading. All the constructors have
the same name as corresponding to the class name that they are differ only
interms of their signature as number of arguments or datatypes or order.
Example:
class
Time1
{
int hour,min,sec;
public Time1()
{
hour=0;
min=0;
sec=0;
}
public Time1(int h)
{
hour=h;
min=0;
sec=0;
}
public Time1(int h, int m)
{
hour=h;
min=m;
sec=0;
}
public Time1(int h,int m,int s)
{
hour=h;
min=m;
sec=s;
}
void printdata()
{
System.out.println(hour+"hours:"+min+"minute:"+sec+"sec");
}
}
class
const3
{
public static void main(String[]
args)
{
Time1 t=new Time1();
t.printdata();
Time1 t1=new Time1(9);
t1.printdata();
Time1 t2=new Time1(7,8);
t2.printdata();
Time1 t3=new
Time1(10,9,4);
t3.printdata();
}
}
No comments:
Post a Comment