As compared to an IS-A relationship, a HAS-A relationship is easy to identify and implement. I hope this statement relieves you! Consider this definition of the bare-bones class Engine:
Of all the preceding classes—Statistics, Car, PartsFactory, and TestCar—only Car shares a HAS-A relationship with the class Engine because Car defines an instance variable of type Engine. Note that it doesn’t matter whether the instance variable engine in class Car is initialized with an object. The HAS-A relationship is shared by the classes.
Case Study 1:
Employee and Department :
packagecom.gs.corejava.composition;publicclassDepratment {privateint dpId;privateString dname;// dept has one empprivateEmply[] emplarray; /** * @return the emply */publicEmply[] getEmply() {return emplarray; } /** * @param emply * the emply to set */publicvoidsetEmply(Emply[] emplarray) {this.emplarray= emplarray; }publicDepratment() { super();// TODO Auto-generated constructor stub }publicDepratment(int dpId,String dname,Emply[] emply) {this.dpId= dpId;this.dname= dname;this.emplarray= emply; } /** * @return the dpId */publicintgetDpId() {return dpId; } /** * @param dpId * the dpId to set */publicvoidsetDpId(int dpId) {this.dpId= dpId; } /** * @return the dname */publicStringgetDname() {return dname; } /** * @param dname * the dname to set */publicvoidsetDname(String dname) {this.dname= dname; }}
packagecom.gs.corejava.composition;//bean pojo modelpublicclassEmply {privateint id;privateString name;privateint age;privatedouble salary;publicEmply() { super();// TODO Auto-generated constructor stub }publicEmply(int id,String name,int age,double salary) {this.id= id;this.name= name;this.age= age;this.salary= salary; } /** * @return the id */publicintgetId() {return id; } /** * @param id * the id to set */publicvoidsetId(int id) {this.id= id; } /** * @return the name */publicStringgetName() {return name; } /** * @param name * the name to set */publicvoidsetName(String name) {this.name= name; } /** * @return the age */publicintgetAge() {return age; } /** * @param age * the age to set */publicvoidsetAge(int age) {this.age= age; } /** * @return the salary */publicdoublegetSalary() {return salary; } /** * @param salary * the salary to set */publicvoidsetSalary(double salary) {this.salary= salary; }}
packagecom.gs.corejava.composition;publicclassCompanyTest {publicstaticvoidmain(String[] args) {Emply emply1 =newEmply(12,"mohit",23,22423423);Emply emply2 =newEmply(14,"rohit",25,234324);Emply[] empArray =newEmply[2]; empArray[0] = emply1; empArray[1] = emply2;Depratment IT =newDepratment();IT.setDpId(133);IT.setDname("IT");IT.setEmply(empArray);dislayDeptDetails(IT); }privatestaticvoiddislayDeptDetails(Depratment iT) {System.out.println("Dept id is "+iT.getDpId());System.out.println("Dept name is "+iT.getDname());Emply[] emplyarr =iT.getEmply();for (Emply emply : emplyarr) {System.out.println("Emp name for IT is "+emply.getName()); } }}