静态方法无法访问类的实例成员 [英] Static method cannot access instance members of a class

查看:229
本文介绍了静态方法无法访问类的实例成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Liang的第9版 Java编程简介中,它指出:静态方法无法访问类的实例成员(第312页)。我知道为什么类的实例成员需要访问方法(可能是静态的),但是为什么方法需要访问实例成员?对我来说,访问是指通过点运算符进行访问。换句话说:

In Liang's 9th edition Introduction to Java Programming it states, "A static method cannot access instance members of a class," (pg 312). I see why an instance member of a class would need to access a method (which might be static), but why would a method need to access an instance member? To me, "access" means "access by way of the dot operator." In other words:

 Class myClass = new Class();
 myClass.someStaticMethod();

很有道理,而:

 someNonStaticMethod.myClass

 someStaticMethod.myClass

不会。是否允许someNonStaticMethod.myClass语法?我相信我从未见过这种格式。如果不允许,为什么要提到静态方法不能访问类的实例成员?

does not. Is the someNonStaticMethod.myClass syntax allowed? I don't believe I've ever seen such formatting. If it is not allowed, why mention that static methods cannot access instance members of a class?

请帮助解除我的困惑。

-DI

推荐答案

访问实例成员意味着访问实例的字段或属性,而不是实例本身,因为它无法编译。点实际上并不意味着以您的正确思维方式进行访问,我想这就是您感到困惑的根源。点用于在特定对象上调用方法(请参见链接)或访问对象的字段(如果该字段是静态的,则访问类)。

Accessing an instance member means accessing a field or attribute of the instance, not the instance itself since that would not compile. A dot does not literally mean "accessing" in the exact way you think and I guess that's the source of confusion you have. The dot is used to call a method on a certain object (see this link) or to access a field of an object (or class if the field is static).

例如,假设该类的定义如下:

For example, assuming the class is defined as follows:

class MyClass {

   private int x;

   static void foo() {
      ... // foo cannot access member x
   }
}

因此在方法 foo 中,您不能引用 x ,因为它是 MyClass 的成员字段,绑定到 MyClass instance $ c>。

So in method foo, you can't reference x because it is a member field of MyClass that is bound to an instance of MyClass.

另请参见了解类成员,以了解静态成员和实例成员之间的区别。

Also see Understanding Class Members to understand the difference between static members and instance members.

这篇关于静态方法无法访问类的实例成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆