Reputation: 4191
The Test3.java:
public class Test3 {
public static void main(String[] args) {
A a = new A();
}
}
class A extends B {
A() {
System.out.println("Now in A()");
}
void m() {
System.out.println("Now in m() of A");
}
}
class B {
B() {
System.out.println("Now in B()");
m();
}
void m() {
System.out.println("Now in m() of B");
}
}
The output:
$ java Test3
Now in B()
Now in m() of A
Now in A()
Why not "Now in m() of B" in the 2nd line of output?
Upvotes: 0
Views: 86
Reputation: 23329
Because methods in Java are virtual
by default, if you using Java 6 or higher, it is recommended that you use the @Override
annotation, it makes things clearer.
The first question is: Why the first line was
Now in B()
The reason is: When you can extend a class in Java a call to the super constructor
will be done automatically for you by the compiler
A() {
super(); // added by Java !!
System.out.println("Now in A()");
}
So, now we are in B's constructor
B() {
System.out.println("Now in B()"); // print this
m(); // Ohh hang on, m() is overridden
}
because m()
is overriden by the subclass A, and the actual instance is of type A, so we will call A's implementation of m(), and that is a polymorphic call.
Upvotes: 2
Reputation: 13596
Because the method m
is overriden in A
. So when it goes to the super constructor, and calls m
, the object is still an instance of A
, so it calls the method in A
.
Upvotes: 3