View RSS Feed

My Java Tips

Constructor calling ordering

Rate this Entry
by , 11-13-2011 at 11:34 AM (898 Views)
Constructors are used for initialization normally. Name of constructor should be same as that of the class. If no constructor is declared, a default constructor is created without parameters. Constructor does not return any thing.


Consider the example below. ClassB inherits from ClassA. In the MainClass, we made an object of ClassB. Default constructor will be called. But the output suggests that first Constructor of ClassA is called and then the constructor of classB is called.

Java Code:
public class ClassA {
public ClassA(){
System.out.println("Constructor of ClassA.");
}
}

public class ClassB extends ClassA {
public ClassB(){
System.out.println("Constructor of ClassB.");
}
}

public class MainClass {
public static void main(String[]str){
ClassB obj = new ClassB();
}
}
Output:


Constructor of ClassA.
Constructor of ClassB.

Now lets do an interesting experiment. We defined a method greetMe with different implementation in ClassA and in ClassB. ClassB inherits from ClassA. In the MainClass, we made an object of ClassB and called the method greetMe(). Method greetMe() defined in classB executes.

Java Code:
public class ClassA {

public void greetMe(){
	System.out.println("Good morning.");
	}
}

public class ClassB extends ClassA {
	public void greetMe(){
		System.out.println("Good afternoon.");
		}
}

public class MainClass {
public static void main(String[]str){
	ClassB obj = new ClassB();
	obj.greetMe();
}
}
Output:


Good afternoon.

In the same example, if we modify ClassB and remove the method from it, we get different output.


public class ClassB extends ClassA {
}

Output:


Good morning.

All these examples have produced interesting results. This shows that constructor calling hierarchy is that constructor of parent is called and then constructor of child gets called. But if you call a method, it is searched in the child class. If not found in the child class, then that method is searched in the parent class.

Submit "Constructor calling ordering" to Facebook Submit "Constructor calling ordering" to Digg Submit "Constructor calling ordering" to del.icio.us Submit "Constructor calling ordering" to StumbleUpon Submit "Constructor calling ordering" to Google

Comments