[英]How to access variable from another class directly(i.e. without using class name or object)?
Suppose, I've a class TestA
which has variable int Age
like - 假设我有一个TestA
类,它的int Age
变量如-
class TestA{
int Age = 25;
}
and I want to access it from class TestB
without using class name(in this case, I'll have to declare Age
as static
) and without creating object of TestA
我想从类TestB
访问它而不使用类名(在这种情况下,我必须将Age
声明为static
)并且不创建TestA
对象
How can we achieve this in Java? 我们如何用Java实现呢?
Note: TestB
is not subclass of TestA
注意: TestB
不是TestA
子类
Define that field as static and do something like: 将该字段定义为静态,然后执行以下操作:
import static TestA.Age;
class TestB {
public void test() {
System.out.println(Age);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.