Seems like a perfectly reasonable run time exception. If your main code was:
public static void main(String[] args){
Integer idObj = new Bar().getId();
int id = idObj; // throws NullPointerException
}
Nobody would be surprised about the null pointer exception. The Bar class returns a null, and a null object pointer can not be turned into a simple value. The implementation of the Bar class might be changed to initialize the id to a non-null value. This block of code can be compiled independently from the Bar class, and so assumptions about the dynamic workings of the Bar class should certainly not be coded into this block of code.
This is probably obvious, but the real solution is to use int
for the id member, instead of Integer
. This, then, has no issue:
private static class Bar{
private final int id;
public Bar(){
this(0);
}
public Bar(int id){
this.id = id;
}
public int getId(){
return id;
}
}
(But I suppose you already were aware of this :-) )