Multiple Contructors (overloaded contructors)

A constructor is a method with the same name of it’s class. The constructor is automatically called when an object is created from the class.

A class file can have multiple constructors, and depending on how many variables are passed, will depend on which constructor is executed.

This allows us to make different objects, with different amoutns of information in it from the same class file.


// jamesprogram.java
class jamesprogram {

public static void main (String[] args){

// looks at the contructor with no arguments in
// the cat.class
cat catObject = new cat();
// uses constructor with 1 agrument
cat catObject2 = new cat(4);
// uses constructor with 2 arguments
cat catObject3 = new cat(2,16);
// uses contructor with 3 arguments
cat catObject4 = new cat(4,54,30);

// returns the cat object that has no arguments
System.out.printf("%s\n",catObject.toTime());
// returns the cat object that has no arguments
System.out.printf("%s\n",catObject2.toTime());
// returns the cat object that has no arguments
System.out.printf("%s\n",catObject3.toTime());
// returns the cat object that has no arguments
System.out.printf("%s\n",catObject4.toTime());

}
}

//cat.java
public class cat {

// we can have constructor
private int hour;
private int minute;
private int second;

// constructor with 0 arguments
public cat(){
this(0,0,0);
}

// constructor with 1 arguments
public cat(int h){
this(h,0,0);
}

// constructor with 2 arguments
public cat(int h, int m){
this(h,m,0);
}

// constructor with 3 arguments
public cat(int h, int m, int s){
setTime(h,m,s);
}

public void setTime(int h, int m, int s){
setHour(h);
setMinute(m);
setSecond(s);
}

//////////////////////////////
// set methods to set the time
// they’re void as they don’t return anything

// setHour method
public void setHour(int h){
hour=((h>=0&&h<24)?h:0); } // setMinute method public void setMinute(int m){ minute=((m>=0&&m<60)?m:0); } // setSecond method public void setSecond(int s){ second=((s>=0&&s<60)?s:0); } /////////////////////////////// // get methods to get the time // getHour method public int getHour(){ return hour; } // getMinute method public int getMinute(){ return minute; } // getSecond method public int getSecond(){ return second; } // display method public String toTime(){ return String.format("%02d:%02d:%02d",getHour(), getMinute(), getSecond()); } } [/java] Outputs: 00:00:00 04:00:00 02:16:00 04:54:30 So, when for example System.out.printf("%s\n",catObject3.toTime()); This object has 2 parameters declared, so it uses the method in the cat.class that takes 2 parameters. // constructor with 2 arguments public cat(int h, int m){ this(h,m,0); } This contructor will add a zero to the 3rd argument as stated in the 'this part'

Leave a Reply