要调用其他类中的变量,必须先实例化该类对象,然后通过对象来访问该类中的变量。
例如,假设有一个名为OtherClass
的类,其中有一个变量intVar
:
public class OtherClass {
public int intVar;
public OtherClass(int value) {
this.intVar = value;
}
}
然后在另一个类中调用OtherClass
中的变量intVar
:
public class MainClass {
public static void main(String[] args) {
OtherClass otherObj = new OtherClass(10);
int value = otherObj.intVar;
System.out.println(value);
}
}
在上面的例子中,我们首先创建了一个OtherClass
的对象otherObj
,然后通过该对象来访问intVar
变量的值,并将其赋给value
变量。最后打印输出value
的值为10。