Java – polymorphism and constructors
I'm a java student. I'm taking an exam When I encounter this problem, I don't understand the answer:
Consider the following categories:
public class A { public A() { methodOne(); } public void methodOne() { System.out.print("A"); } } public class B extends A { public B() { System.out.print("*"); } public void methodOne() { System.out.print("B"); } }
What is the output when executing the following code?
A obj = new B();
The correct answer is b * Can someone explain to me the order of method calls?
Solution
Call the B constructor The first implicit instruction of the B constructor is super () (calling the default constructor of the super class) So the constructor of a is called A's constructor calls super (), which calls Java that doesn't print anything Lang. object constructor Then call methodOne (). Since the object is of type B, call the methodone version of B and print B. then the B constructor continues to execute and * is printed
It must be noted that calling an overridable method from a constructor (such as a's constructor) is a very bad practice: it calls the method of an object that has not been constructed