I have class A which extends the Activity class. This class is in package aaa. I have class B which is in package aaa.extensions. What is the best way to access variables in class A?
如果您的类B是在类A中创建的,则通常可以通过将类A的实例传递给类B的构造函数来解决,因此类B的新实例可以在内部使用类A的实例。
Either I am not understanding well the question or it is really basic. What you need to do is provide access methods in your class A so any other class in whatever package it is could have access to that "variable" declared inside your class A by just giving an instance of A to any other class that wants/needs to access its internal state.
class A {
private String name; // internal private attribute (variable) for class A
public String getName() { // public access method for attribute "name"
return name;
}
}
class B {
private A instanceOfA; // internal private reference to class A
public B(A instanceOfA) { // public constructor of class B, which requires an instance of A as a parameter
this.instanceOfA = instanceOf;
}
public void doNothing() { // example method accessing A's attribute "name"
System.out.println(instanceOfA.getName());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.