Has-A Relationship in Java
In Java, a Has-A relationship is also known as composition. It is also used for code reusability in Java. In Java, a Has-A relationship simply means that an instance of one class has a reference to an instance of another class or an other instance of the same class. For example, a car has an engine, a dog has a tail and so on. In Java, there is no such keyword that implements a Has-A relationship. But we mostly use new keywords to implement a Has-A relationship in Java.
Consider we are storing the information of the student, then we may create a class like below –Class Student { int roll; String sname; Address address; }
In the above class we have entity reference “Address” which stores again its own information like street,city,state,zip. like below –
Class Address { String street; String state; String zip; String city; }
so we can say that Student HAS-A Address Thus if the class has entity reference then entity will represent the HAS-A relationship.
Consider the following example –
Address.java
public class Address { String street; String city; String state; String zip; public Address(String street, String city, String state, String zip) { this.street = street; this.city = city; this.state = state; this.zip = zip; } }
Student.java
public class Student { int roll; Address address; Student(int rollNo,Address addressDetail){ roll = rollNo; address = addressDetail; } void printStudentDetails(Address address1) { System.out.println("Roll : " + roll); System.out.println("Street : " + address1.street); System.out.println("City : " + address1.city); System.out.println("State : " + address1.state); System.out.println("Zip : " + address1.zip); } public static void main(String[] args) { Address address1; address1 = new Address("1-ST","PN","Mah","41"); Student s1 = new Student(1,address1); s1.printStudentDetails(address1); } }
Output :
Roll : 1 Street : 1-ST City : PN State : Mah Zip : 41
0 comments:
Post a Comment
Let us know your responses and feedback