Search code examples
javaconstructorinstancecomposition

Java composition - Constructor


Today I came across composition. From what I understand, for each instance of composition I need to create new object in constructor, like this :

public class Human {
   private String name;
   private Adress adress;

   public Human (String name, Adress adress) {
      this.name = name;
      this.adress = new Adress(adress);
   }
}

So if I would create a new instance of class human, I would need to assign to it some instance of adress, or create completely new adress, and the constructor would look like this

public class Human {
   private String name;
   private Adress adress;

   public Human (String name, String city, String country) {
      this.name = name;
      this.adress = new Adress(city, country);
   }
}

First of all, are those codes correct? And also is there any option, that if I would create new instance of class human, the atribute Adress would be empty, and I could set it later by using set method? Thank you very much for your response.


Solution

  • A new object is not mandatory in general, however, if you want to have the adress of human immutable (only if Adress is already not immutable), it is a good practice to kill all the references to it from outside the object.

    That's indeed the rule for a composition.

    This is naturally the way to do it, if adress takes an adress as input within its constructor.

    public class Human {
        private String name;
        private Adress adress;
    
        public Human (String name, Adress adress) {
            this.name = name;
            this.adress = new Adress(adress); 
        }
    }
    

    If you want, you could have a set of different constructors and set some of the fields later

    public class Human {
        private String name;
        private Adress adress;
    
        public Human() {}
        public Human(String name){
            this.name = name;
        }
        public Human(String name, Adress adress) {
            this.name = name;
            this.adress = adress; // or new Adress(adress)
        }
    
        public void setAdress (Adress adress) {
            this.adress = adress;
        }
    }