Constructors

Constructors are special methods that have the same name as the class itself. They were mentioned briefly in chapter 4, but they are worth looking at in detail as almost any non trivial Java program will use them. In addition to having the same name as the class a constructor must have no return type.

Thus in the following class the method MyCon is not a constructor.

public class MyCon{
	public static void main(String argv[]){
		MyCon mc = new MyCon();	
	}
	public void MyCon(){
		System.out.println("MyCon");
	}
}

If you compile and run this code you will find that there is no output, because method MyCon has a return type of void, which means it is not a constructor.

Overloading Constructors

Constructors can be overloaded in a similar way to methods. Constructors are used to initialize classes, and it is common to want more than one way of initialize an instance of a class. Thus you might have a quiz class you might have one version that included a userid and one that had no associated user. Thus you could have classes as follows.

public class Quiz{
    Quiz(int iSubjectid, int iUserid){
	/* constructor body */
    }
    Quiz(int iSubjectId){
	/* no userid in this version */
    }
    
}

Both of the following lines of code will instantiate Quiz objects.

Quiz q = new Quiz(1,1);
Quiz q2 = new Quiz(1);

Once you get used to overloaded constructors it is hard to imagine writing code without them. I have written code using PHP4 and found the lack of overloaded constructors to be quite frustrating.

Last modified: Sunday, 20 September 2015, 07:21 PM