Constructor calling ordering
7 December 2007Constructors 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.
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.
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.
Related Posts:
- Writing MIDlet for SMS - III
- Returning multiple results (JDBC 3.0)
- Singleton - Creational Design Pattern (II)
- Calling stored procedures
- Avoid unnecessary method calls
- Asynchronous method calls - I
- Annotating an annotation- II
- Defining own Exceptions
- Record Management System (III)
- More on Collection FrameWork
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Constructor calling ordering