Search code examples
javaobjectencapsulation

Call object created from another class


I need ClassB to get the object created from ClassA, which is u. How do I do that? ClassA sets the value using setSomething() from Utility class, while ClassB should get the value set by ClassA using the getSomething() of the same object(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;
   }

}

Solution

  • Straightforward approach without patterns and simple classes.

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

    Should print out 'David';