Reputation: 2420
While the object is being constructed, can it be null ?
class Sample {
public Sample() {
if( this != null ) { // Is this check necessary anywhere in the constructor?
this.doSomething();
}
}
....
....
}
Upvotes: 2
Views: 161
Reputation: 1502076
this
won't be null - but if you call a non-final instance method from a constructor, you should document that really thoroughly, as any subclass constructors won't have been run yet. That means if doSomething()
is overridden in a subclass, it will see the default values for any fields declared in that subclass (where the default is the default value for the type, not whatever the variable initializer might show). Basically it's worth trying to avoid calling non-final instance methods in constructors if at all possible.
Upvotes: 4
Reputation: 206896
The this
reference is never null
in Java, also not in the constructor. However, it's normally not a good idea to call non-final methods that might have been overridden in subclasses from the constructor, because the subclass-part of the object will not yet have been initialized.
An example:
class Superclass {
public Superclass() {
// NOTE: This will print null instead of "Jack", because the subclass constructor has not yet been run!
printName();
}
public void printName() {
System.out.println("Superclass method");
}
}
public class Subclass extends Superclass {
private final String name;
public Subclass() {
name = "Jack";
}
@Override
public void printName() {
System.out.println(name);
}
public static void main(String[] args) {
new Subclass();
}
}
Upvotes: 1
Reputation: 308131
No, this
can't ever be null
in a constructor in Java.
In fact this
can't ever be null
in Java. Anywhere.
At any given point in Java you are either in an object context and have access to a non-null
this
, or you are in a static context and can't access this
at all, but it can never be null
.
Upvotes: 3