![](/img/trans.png)
[英]Is it necessary for instance methods to access instance variable in java?
[英]is it possible to access instance methods and variable via class methods
直到我在Oracle Doc上读到这个(类方法不能直接访问实例变量或实例方法 - 它们必须使用对象引用)我唯一知道的,关于实例方法和变量不能被类(静态)方法访问直。
当它说......他们必须使用对象参考时意味着什么? 这是否意味着我们可以使用类方法间接访问实例变量和方法?
先感谢您。
这意味着允许这样做:
public class Test {
public int instanceVariable = 42;
public void instanceMethod() {System.out.println("Hello!");}
public static void staticMethod() {
Test test = new Test();
System.out.println(test.instanceVariable); // prints 42
test.instanceMethod(); // prints Hello!
}
}
这不是:
public class Test {
public int instanceVariable = 42;
public void instanceMethod() {System.out.println("Hello!");}
public static void staticMethod() {
System.out.println(instanceVariable); // compilation error
instanceMethod(); // compilation error
}
}
顾名思义,实例变量与类的实例相关联。 因此,直接从类方法访问它,这与任何特定实例无关,这没有意义。 因此,要访问实例变量,您必须具有从中访问实例变量的类的实例。
但事实并非如此 - 类变量位于“顶级”,因此实例方法和变量可以访问。
class MyClass;
{
public int x = 2;
public static int y = 2;
private int z = y - 1; //This will compile.
public static void main(String args[])
{
System.out.println("Hello, World!");
}
public static void show()
{
System.out.println(x + y); // x is for an instance, y is not! This will not compile.
MyClass m = new MyClass();
System.out.println(m.x + y); // x is for the instance m, so this will compile.
}
public void show2()
{
System.out.println(x + y); // x is per instance, y is for the class but accessible to every instance, so this will compile.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.