Consider the following code
package example0;
public class Main {
static class A {
private final String var;
public A() {
var = getVar();
System.out.println("var string length is " + var.length());
}
public String getVar() {
return "String from A";
}
}
static class B extends A {
private final String bString;
public B() {
bString = "String from B";
}
@Override
public String getVar() {
return bString;
}
}
public static void main(String[] args) {
B b = new B();
}
}
Currently, in my opinion, there are two ways to avoid such a problem.
Or make class A the final class.
static final class A {
private final String var;
public A() {
var = getVar();
System.out.println("var string length is " + var.length());
}
public String getVar() {
return "String from A";
}
}
or
Creating the getVar final method
static class A {
private final String var;
public A() {
var = getVar();
System.out.println("var string length is " + var.length());
}
public final String getVar() {
return "String from A";
}
}
The author is trying to suggest ways to prevent the above problems. However, the decision seems cumbersome because there are some rules that must be followed.
http://benpryor.com/blog/2008/01/02/dont-call-subclass-methods-from-a-superclass-constructor/
Besides creating the final method proposed by the author, are there more ways to prevent the problem described above (not calling subclass methods from the superclass constructor)?
source
share