Javatpoint Logo

91-9990449935

 0120-4256464

Constructor Injection with Dependent Object

If there is HAS-A relationship between the classes, we create the instance of dependent object (contained object) first then pass it as an argument of the main class constructor. Here, our scenario is Employee HAS-A Address. The Address class object will be termed as the dependent object. Let's see the Address class first:

Address.java

This class contains three properties, one constructor and toString() method to return the values of these object.

Employee.java

It contains three properties id, name and address(dependent object) ,two constructors and show() method to show the records of the current object including the depedent object.

applicationContext.xml

The ref attribute is used to define the reference of another object, such way we are passing the dependent object as an constructor argument.

Test.java

This class gets the bean from the applicationContext.xml file and calls the show method.