简体   繁体   English

如何直接从另一个类访问变量(即不使用类名或对象)?

[英]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.

相关问题 如何在不创建新对象的情况下从另一个类访问变量 - How to Access Variable from Another Class without Creating New Object 识别对象类型(即类) - Identify Object Type(i.e. Class) 如何从另一个类访问对象(例如ArrayList)? - How can I access an object (e.g. ArrayList) from another class? 如何在不使用静态上下文的类名的情况下访问Java中的.class对象 - How to access the .class object in java without using the class name from a static context 如何通过将值从另一个变量传递给对象来访问类变量? - How to access a class variable by passing value to object from another variable? 如何在不创建新对象的情况下从另一个类访问非静态变量 - How to Access non static variable from Another Class without Creating New Object 在另一个类函数中访问动态组件(即新标签)? - Access dynamic component (i.e. new Label) in another class function? 如何在不创建对象的情况下从另一个类获取变量 - How to get a variable from another class without creating an object 当我从另一个类调用对象时出现错误,即“找不到符号” - Error comes when i call objects from another class i.e. “cannot find symbol” 如何在不创建新实例的情况下从另一个类访问变量 - How do I access a variable from another class without it creating a new instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM