Class A calls the public method f() in the Constructor. Class B overrides method f() with its own implementation.
Suppose you intantiate Object B.. method f() of Object B would be called in the Constructor of Object A, although Object B is not fully initialized.
Can anyone explain this behavior?
EDIT: Yes, it's not recommended practice.. yet i don't understand why Java is not calling the f() implementation of the base-Class A instead of "reaching out" to the f() implementation of the derived Class B.
Code:
class A {
A() {
System.out.println("A: constructor");
f();
}
public void f() {
System.out.println("A: f()");
}
}
class B extends A {
int x = 10;
B() {
System.out.println("B: constructor");
}
@Override
public void f() {
System.out.println("B: f()");
this.x++;
System.out.println("B: x = " + x);
}
}
public class PolyMethodConst {
public static void main(String[] args) {
new B();
}
}
Output:
A: constructor
B: f()
B: x = 1
B: constructor
解决方案
You're correct, that is the way it works. It's not recommended practice though, because somebody who inherits from your class can unintentionally break it.