调用从另一个类创建的对象

时间:2015-01-22 09:51:39

标签: java object encapsulation

我需要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;
   }

}

2 个答案:

答案 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();
   }
}