易百教程

54、可以将引用分配给this变量吗?

不能。this不能分配给任何值,因为它始终指向当前类对象,并且this是 Java 中的最终引用。 但是,如果我们尝试这样做,则会显示编译器错误。 考虑以下示例:

public class Test  
{  
    public Test()  
    {  
        this = null;   
        System.out.println("Test class constructor called");  
    }  
    public static void main (String args[])  
    {  
        Test t = new Test();  
    }  
}

运行出错:

Test.java:5: error: cannot assign a value to final variable this
        this = null; 
        ^
1 error