Why does the code throw null pointer Exception and what is the meaning of using ‘this’. I am beginner, value any help.
// class Foobar
private Foo f;
void get(){
this.getFoo().handle();
}
public Foolish getFoo(){
return this.f;
}
void handle(){
System.out.println("handle of the intrf");
}
// please note that
public interface Foolish {
void handle();
}
//main
public static void main(String[] args) {
new Foobar().get();
The reason that you get an exception is that the member
fof typeFoois not initialized to, say,new Foo()somewhere in the constructor or in the declaration.The reference to
thisin this context means “the object itself”; it is entirely not necessary in your code, because there is nothing to disambiguate.