Suppose I have two classes defined the following way:
public class A {
public A() {
foo();
}
public void foo() {
System.out.println("A");
}
}
public class B extends A {
private String bar;
public B() {
bar = "bar";
}
@Override
public void foo() {
System.out.println(bar);
}
}
And then i instantiate B the following way:
A test = new B();
So why can’t the compiler respectively the IDE warn me that there will be a NullPointer in the foo method of B? That wouldn’t be to difficult to check and sometimes very useful.
While this is a design error, it’s not a grammatical error.
Here’s some quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:
An obedient compiler would let it compile just fine, since it is linguistically legal. Fortunately, code analysis tools can be used to find these design errors, e.g.
findbugs: