Reputation: 3071
Assume I have the following class:
public abstract class Test {
private List<String> strings = new ArrayList<>();
// to be called concurrently
public int getStringsSize() {
return strings.size();
}
}
Is there a chance that getStringsSize()
will throw NPE for some subclass of Test
? Or what else can go wrong? As far as I understand there're no Java Memory Model guarantees about such case.
Upvotes: 1
Views: 86
Reputation: 140573
The point is: when a subclass object gets instantiated, the super constructor and super field init statements will be executed before any subclass code is executed. See here or there for more information. In other words: before a client that creates a subclass via new gets access to the newly created object, it is guaranteed that those init statements were executed.
And as we are talking about a single private field that only lives in the super class, there is no chance for that method call to produce an NPE
Unless you have some other method that resets the field to null. Which you can avoid by using the final keyword for that field (which is good practice anyway: make it your default to put final on fields).
Finally; for completeness: it is possible to write super/subclass code that fails when doing new
on the subclass because of "something not initialized yet" - like when your super class constructor calls a method that is overridden in the subclass. But that is like: bad practice (as it can lead to such bizarre errors). So don't even think about doing that.
Upvotes: 2
Reputation: 6329
getStringSize()
would only throw NPE if you set strings
to null
manually, EG in a setStrings()
method. getStringSize()
should also be set final
.
The initializer runs at instantiation time, that is after the super(...)
constructor, but before the first instruction of this(...)
constructor.
Upvotes: 1
Reputation: 12493
No. As long as the strings
field is not reassigned (which can never be done by a subclass since it is private), then it will never be accessed in a null state, no matter how many threads try to access it. And as such, strings.size()
can never throw a NullPointerException
.
Upvotes: 1