I'll start with an example code:
class A {
public A() {
f();
}
public void f() {}
}
class B extends A {
private Object o;
public B() {
super();
o = new Object();
}
@Override
public void f() {
o.hashCode();
super.f();
}
}
public class Init {
public static void main(String[] args) {
B b = new B();
}
}
This program throws NullPointerException. When an object b enters the constructor of its superclass Aand calls a method call f()that is overridden by class B B.f(), instead of A.f()what I would expect.
I thought that the superclass should not have known if it was a subclass or not, but of course, this can be used by the class to determine if it was a subclass or not? What is the reason for this? Is there any workaround if I really want to be A.f()called instead B.f()?
Thanks in advance.
Next question:
. , , . , , , , . "" , . :
class A {
private boolean isSubclassed = true;
public A() {
f();
if(this.isSubclassed) {
System.out.println("I'm subclassed.");
} else {
System.out.println("I'm not subclassed.");
}
}
public void f() {
this.isSubclassed = false;
}
}
class B extends A {
public B() {
super();
}
@Override
public void f() {}
}
public class Init {
public static void main(String[] args) {
new B();
new A();
}
}
:
I'm subclassed.
I'm not subclassed.
A , . , . ? ?