Is it true only in Inheritance or most of the cases ?
public class MyClass {
public int id;
public MyClass() {
// Some stuff
setI
You should not call an overridable method from a constructor.
If you call a method that can be overridden by a subclass in a costructor, than the subclass might access variables of the superclass that have not been initialized yet.
For example the following code looks good so far
class MyClass {
public int id;
protected String someStr;
public MyClass() {
SetId(5);
someStr = "test";
}
public void SetId(int Id) {
id = Id;
}
}
If you now subclass MyClass and override the SetId method you might access the superclass's someStr variable which has not been initialized yet and thus will cause a NullPointerException in this case.
class MySubClass extends MyClass {
public void SetId(int Id) {
id = Id;
someStr.toString(); // will cause NullPointerException
}
}
The cause of the NPE might be hard to see if there is a bigger inheritence hierarchy.