While the object 开发者_如何学Pythonis being constructed, can it be null ?
class Sample {
public Sample() {
if( this != null ) { // Is this check necessary anywhere in the constructor?
this.doSomething();
}
}
....
....
}
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.
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
.
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();
}
}
精彩评论