我需要ClassB
来获取从ClassA
创建的对象,即u
。我怎么做? ClassA
使用setSomething()
类中的Utility
设置值,而ClassB
应使用同一对象的ClassA
获取getSomething()
设置的值(u
)
public class ClassA
{
Utility u = new Utility()
u.setSomething("David");
}
public class ClassB
{
//How do I get the 'u' Utility object from ClassA
}
public class Utility
{
private String fullName;
public void setSomething(String name)
{
this.fullName = name
}
public String getSomething()
{
return fullName;
}
}
答案 0 :(得分:1)
没有模式和简单类的直接方法。
public class ClassA {
private Utility u = new Utility()
public ClassA() {
u.setSomething("David");
}
public Utility getU() {
return u;
}
}
public class ClassB {
private ClassA classA = new ClassA();
public ClassB() {
System.out.println(classA.getU().getSomething());
}
}
public class Utility {
private String fullName;
public void setSomething(String name) {
this.fullName = name;
}
public String getSomething() {
return fullName;
}
}
public static void main(String[] args) {
ClassB b = new ClassB();
}
应该打印出'David';
答案 1 :(得分:1)
请注意,没有一种方法可以做。有一种方法可以做得更好。这完全取决于您的设计和需求,这只是一个例子:
public class ClassA{
Utility u = new Utility()
public Utility getU(){
return u;
}
public void buildB(){
ClassB classB = new ClassB(this);
}
}
public class ClassB{
ClassA classA;
Utility u;
public ClassB(ClassA classA){
this.classA = classA;
u = classA.getU();
}
}