2012-02-16 32 views
-2

为什么代码会抛出空指针异常以及使用'this'的含义是什么。我是初学者,重视任何帮助。在下列情况下使用关键字'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

哪条线投掷? – JaredPar 2012-02-16 16:43:52

+0

???没有意义...请发布完整的堆栈跟踪。 – m0skit0 2012-02-16 16:44:48

+0

请显示完整的堆栈跟踪 – amit 2012-02-16 16:45:00

回答

1

,你会得到一个异常的原因是该成员Foo类型的f没有初始化,比方说,new Foo()在某处构造函数或声明中。

本文中对this的引用意味着“对象本身”;在您的代码中完全没有必要,因为没有什么可以消除歧义。

1

因为fnullhandle()getFoo()返回后调用就可以了。

0

你永远初始化富,你需要像下面

foo = new Foo(); 
+0

不要。它会导致无限的递归构造函数调用 – amit 2012-02-16 16:46:40

0

这意味着它返回了类Foobar的当前实例的变量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 
    } 
1

它看起来并不像“私人富f被初始化过这样this.getFoo返回null,“null'.handle()会抛出异常。

相关问题