是否可以通过类方法访问实例方法和变量 [英] is it possible to access instance methods and variable via class methods
本文介绍了是否可以通过类方法访问实例方法和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
直到我在Oracle Doc上阅读了这本书(类方法无法直接访问实例变量或实例方法,它们必须使用对象引用),这是我唯一了解的有关类无法访问实例方法和变量的信息(静态)方法.
Till I read this on Oracle Doc (Class methods cannot access instance variables or instance methods directly—they must use an object reference) the only thing I know, about instance methods and variables are not able to be accessed by the class(static) methods directly.
当说"....它们必须使用对象引用"时是什么意思?这是否意味着我们可以使用类方法间接访问实例变量和方法?
What does it mean when it says ....they must use an object reference? Does it mean we can access instance variables and methods indirectly using class methods?
先谢谢您.
推荐答案
这表示允许这样做:
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
}
}
这篇关于是否可以通过类方法访问实例方法和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文