为什么代码抛出空指针Exception以及使用'this'的含义是什么。我是初学者,重视任何帮助。
// 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();
答案 0 :(得分:1)
因为f
是null
handle()
,getFoo()
在{{1}}返回后调用了{{1}}。
答案 1 :(得分:1)
您获得异常的原因是类型f
的成员Foo
未在构造函数或声明中的某处初始化为new Foo()
。
在此上下文中对this
的引用意味着“对象本身”;在你的代码中完全没有必要,因为没有什么可以消除歧义。
答案 2 :(得分:1)
看起来'private Foo f'看起来没有被初始化,所以this.getFoo返回null,'null'。handle()会抛出异常。
答案 3 :(得分:0)
你永远不会初始化foo,你需要类似下面的内容,
foo = new Foo();
答案 4 :(得分:0)
这意味着它将返回班级f
的当前实例的变量Foobar
。这里,它是多余的,因为f
不明确(没有定义本地f
变量)。考虑
class A {
private int b = 1;
public int m()
{
int b = 2;
return b; // will return 2
}
public int n()
{
int b = 2;
return this.b; // will return 1
}