Constructor Overloading Example and Issues

Take the following example:

public class ContructorExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Person me = new Person("James", "Froggatt");
		System.out.println(me.firstName + " " + me.lastName);
		
		Person you = new Person("Emma");
		System.out.println(you.firstName + " " + you.lastName);
	}
}


class Person {
	
	String firstName;
	String lastName;
	
	// Constructor
	Person (String fn, String ln){
		firstName=fn;
		lastName=ln;
	}
	
	// Constructor
	Person (String fn){
			firstName=fn;
			lastName="NA";
	}
}

Outputs:

James Froggatt
Emma NA

If we change the Person class to:

class Person {
	
	String firstName;
	String lastName;
	
	// Constructor
	Person (String fn, String ln){
		firstName=fn;
		lastName=ln;
	}
	
	// Constructor
	Person (String fn){
			firstName="Mrs " + fn;
			lastName="NA";
	}
}

…we can see in the second constructor, our firstName is not consistent in both constructors. This would output:

James Froggatt
Mrs Emma NA

In the above example, the firstName is getting different values depending on whether the first or second constructor is called. This is inconsistent. How do we fix this inconsistency?

We need to create consistent parameterised constructors, and we can do this using “this”

class Person {
	
	String firstName;
	String lastName;
	
	// Constructor
	Person (String fn, String ln){
	        System.out.println("Parameterised constructor called here");
		firstName=fn;
		lastName=ln;
	}
	
	// Constructor
	Person (String fn){
		this(fn,"NA");
	}
}

Notice here the “this” statement. By using “this”, you’re actually calling the constructor above that takes two arguments

It outputs:

Parameterised constructor called here
James Froggatt
Parameterised constructor called here
Emma NA

No matter how many constructors you define, ensure they are consistent!

** Use the “this” keyword to get the code to read the constructor with the most arguments, try to call the biggest one. The benefit of this is that you will write the code in 1 place and everyone’s going to run the same constructor and hence no matter which constructor your objects use, the data will always be consistent **

Leave a Reply