Java 使用关键字';这';在下面的上下文中暗示
为什么代码抛出空指针异常?使用“this”的含义是什么。我是初学者,很重视任何帮助Java 使用关键字';这';在下面的上下文中暗示,java,Java,为什么代码抛出空指针异常?使用“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 p
// 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();
因为
f
是null
并且handle()
在被getFoo()
返回后被调用,所以您永远不会初始化foo,您需要如下内容:
foo = new Foo();
出现异常的原因是
Foo
类型的成员f
未初始化为构造函数或声明中的某个位置,例如new Foo()
在本上下文中,对该的引用意味着“对象本身”;它在代码中完全没有必要,因为没有什么可以消除歧义。这意味着它将返回类的当前实例的变量
f
。在这里,它是多余的,因为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
}
“private Foo f”似乎从未初始化过,因此this.getFoo返回null和“null”。handle()将引发异常。???没有道理。。。请发布完整的堆栈跟踪。请显示完整的堆栈跟踪始终确保检查
如果(this!=null)
(开玩笑)不要。它将导致无限递归构造函数调用