简体   繁体   English

非静态方法如何访问java中的静态成员?

[英]How does non-static method access static members in java?

Consider this: 考虑一下:

class SomeClass
{
   static int a;
   int method()
   {
      int b = a;
      return b;
   }
}

How does a is being accessed in method? 如何a是正在方法来访问? Is it this.a or someClass.a ? 它是this.asomeClass.a

EDIT: Sorry if I'm not clear in my question. 编辑:对不起,如果我不清楚我的问题。 What I want to know is: *Is there a hidden this or someClass associated with a [in method ] or is it simply a [in method ] that is accessing the class member? 我想知道的是:*是否有一个 [在方法 ]关联的隐藏SomeClass的或者是一个简单 [在方法 ]正在访问类的成员?

It's just a : the same field for any instance of the class. 它只是a :类的任何实例的相同字段。 You can write someClass.a if you need an explicit disambiguation. 如果需要明确的消歧,可以编写someClass.a

Consider carefully why you would want a non-static method that returns a static member though: it seems like a code "smell" to me. 仔细考虑为什么你需要一个非静态方法来返回一个静态成员:它看起来像一个代码“闻到”我。

I will edit your example in order to make it look a little bit more right: 我将编辑您的示例,以使其看起来更正确:

public class SomeClass
{
   private static int a = 1;
   public int method()
   {
      int b = a;
      return b;
   }
}

int b = a; is equal to int b = SomeClass.a; 等于int b = SomeClass.a;

Don't be confused with this - it is a reference to an object. 不要与this混淆 - 它是对象的引用。 Static fields belong to a class, not to an object, so it is incorrect to get a with this.a 静态字段属于一类,而不是一个对象,因此它是不正确的得到athis.a

And, as already mentioned here : 而且,正如这里已经提到的:

Instance methods can access class variables and class methods directly. 实例方法可以直接访问类变量和类方法。

If you're inside the class you can access it by just calling a 如果你的类中,你可以通过只调用访问a

From any other class you'll receive this static member by using someClass.a 从任何其他类,您将通过使用someClass.a接收此静态成员

As long as the static member is public, you can use "SomeClass.a" from any class. 只要静态成员是公共的,您就可以使用任何类中的“SomeClass.a”。 For private members, create an accessor method if you really need to access the member and from within the class, just specify it as "a". 对于私有成员,如果您确实需要访问该成员并在该类中,请创建一个访问器方法,只需将其指定为“a”即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM