IS-A and HAS-A Relationships in Java – Code Example

Code reuse-ability is the fundamental objective of object oriented programming. To achieve code reuse-ability objective, we use IS-A, HAS-A relationships. IS-A relationship is another name of inheritance or we can say that IS-A relationship is achieved through inheritance.

In inheritance child class can inherit attributes and methods from its parent class. For example we have a Student class which inherits from Human class then it means that it follows the IS-A relationship because a Student IS-A Human. Further it should be noted that a Student IS-A Human but a Human may not be a Student. It means that child class can inherit attributes and methods from parent class but parent class cannot inherit attributes and methods from child class.

Another way to achieve code reuse-ability objective is to use HAS-A relationship. In HAS-A relationship, we create instance of the class inside another class so that we can use the attributes and methods of that class. Following example code will clear the idea.

[js]
//RelationshipDemo.java which is the main class
package relationshipdemo;
public class RelationshipDemo {
public static void main(String[] args) {
// TODO code application logic here
Student s1 = new Student();
s1.setCNIC(1234);
s1.getCNIC();
s1.setRegNo(456);
s1.getRegNo();
s1.getAttendanceDate();
}
}

//Human.java class

package relationshipdemo;
public class Human {
int cnic;
public void setCNIC(int x){
cnic = x;
}
public void getCNIC(){
System.out.printf("CNIC is: %d", cnic);
}
}

// Student.java class

package relationshipdemo;
public class Student extends Human { // implementing inheritance i.e IS-A relationship
int regNo;
public void setRegNo(int y){
regNo = y;
}
public void getRegNo(){
System.out.printf("Reg No is: %d", regNo);
}
public void getAttendanceDate(){
Attendance a1 = new Attendance(); // creating instance of Attendance class i.e HAS-A relationship
a1.setDate(23);
a1.getDate();
}
}

// Attendance.java class

package relationshipdemo;
public class Attendance {
int date;
public void setDate(int z){
date = z;
}
public void getDate(){
System.out.printf("Date is: %d", date);
}
}
[/js]

OUTPUT:

is-a and has-a relationship in java

Leave a Reply

Your email address will not be published. Required fields are marked *