0

I knew that we can not use this keyword in a static method, But I got confused why we can not use this inside static blocks orstatic methods. Even the same case with super(). Could anyone shed light on this?

Thanks

4

7 回答 7

3

thissuper分别引用当前实例和父实例。

在任何static上下文中,无论是 astatic block还是 a static method,都没有可引用的实例,因此不允许使用关键字。

super()是对父实例的无参数构造函数的调用,并且只允许作为构造函数中的第一条语句,这使其无法出现在任何静态上下文中。

于 2013-05-28T14:31:51.747 回答
3

根据文档

在实例方法或构造函数中,this 是对当前对象的引用——调用其方法或构造函数的对象。您可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。

但是静态方法与类有关,而不与对象有关。在静态方法中,您没有任何实例。

于 2013-05-28T14:32:18.167 回答
0

To answer this we should consider what static means - it means that this bit is put in a 'static' place in memory, it exists only once.

So every class has static bits and non-static bits. The static bits exist once and the non-static bits can exist many times (i.e. lots of different instances). The word 'this' can then be thought of as shorthand for 'this version of the non-static bits'.

In a static context we have no version of the non-static bits to refer to (or to be more precise we don't know which version we should refer to!) so we have no this. The same argument can be made for super.

于 2013-05-28T14:41:44.930 回答
0

例如,静态块可用于初始化静态变量。

静态方法也不能在实例范围内工作。

两者都只与类相关,与该类的实例没有任何关系。

于 2013-05-28T14:33:14.440 回答
0

根据定义,静态方法和块与类相关联,而不是与此类的任何实例相关联。

对于this当前对象实例,您不能在任何静态初始化块或方法中使用它是完全正常的。

于 2013-05-28T14:31:50.533 回答
0

因为 this 指向类的一个实例,所以在静态方法/块中你没有实例。

于 2013-05-28T14:32:05.753 回答
0

根据甲骨文

在实例方法或构造函数中,this是对当前对象的引用——正在调用其方法或构造函数的对象。

因此,在静态类中,您没有创建实例变量对象。这就是为什么你不能使用this关键字

于 2013-05-28T14:32:10.410 回答