非静态方法如何访问java中的静态成员?
How does non-static method access static members in java?
考虑一下:
class SomeClass
{
static int a;
int method()
{
int b = a;
return b;
}
}
如何在方法中访问 a
?是 this.a
还是 someClass.a
?
编辑: 对不起,如果我的问题不清楚。我想知道的是:*是否有一个隐藏的this或someClass与a[in method] 或者只是 a [in method] 访问 class成员?
如果您在 class 中,只需调用 a
即可访问它
从任何其他 class 您将通过使用 someClass.a
收到此静态成员
它只是 a
:与 class 的 any 实例相同的字段。如果需要明确的消歧,可以写someClass.a
。
仔细考虑 为什么 你会想要一个非静态方法,但 returns 是一个静态成员:对我来说它看起来像一个代码 "smell"。
我将编辑您的示例以使其看起来更正确一些:
public class SomeClass
{
private static int a = 1;
public int method()
{
int b = a;
return b;
}
}
int b = a;
等于 int b = SomeClass.a;
不要与 this
混淆 - 它是对对象的引用。静态字段属于一个class,不属于一个对象,所以用this.a
得到a
是不正确的
并且,如前所述here:
Instance methods can access class variables and class methods
directly.
只要静态成员是 public,您就可以使用任何 class 中的 "SomeClass.a"。对于私有成员,如果您确实需要访问该成员并从 class 中创建一个访问器方法,只需将其指定为 "a".
考虑一下:
class SomeClass
{
static int a;
int method()
{
int b = a;
return b;
}
}
如何在方法中访问 a
?是 this.a
还是 someClass.a
?
编辑: 对不起,如果我的问题不清楚。我想知道的是:*是否有一个隐藏的this或someClass与a[in method] 或者只是 a [in method] 访问 class成员?
如果您在 class 中,只需调用 a
从任何其他 class 您将通过使用 someClass.a
它只是 a
:与 class 的 any 实例相同的字段。如果需要明确的消歧,可以写someClass.a
。
仔细考虑 为什么 你会想要一个非静态方法,但 returns 是一个静态成员:对我来说它看起来像一个代码 "smell"。
我将编辑您的示例以使其看起来更正确一些:
public class SomeClass
{
private static int a = 1;
public int method()
{
int b = a;
return b;
}
}
int b = a;
等于 int b = SomeClass.a;
不要与 this
混淆 - 它是对对象的引用。静态字段属于一个class,不属于一个对象,所以用this.a
a
是不正确的
并且,如前所述here:
Instance methods can access class variables and class methods directly.
只要静态成员是 public,您就可以使用任何 class 中的 "SomeClass.a"。对于私有成员,如果您确实需要访问该成员并从 class 中创建一个访问器方法,只需将其指定为 "a".