Java Tutorial

Is-A & Has-A

IS-A Relationship :

This refers to inheritance or implementation. Expressed using keyword "extends". Main advantage is code reusability.

HAS-A Relationship :

Has-A means an instance of one class "has a" reference to an instance of another class or another instance of same class.

It is also known as "composition" or "aggregation". There is no specific keyword to implement HAS-A relationship but mostly we are depended upon "new" keyword.

package com.ashish.poc;

class Person {

    public String name;
    public String fname;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public void showPersonDetails() {
        System.out.println("Name:" + this.name);
        System.out.println("FName:" + this.fname);
    }
}


/*
 * this is example of Is-A
 * here we are extending the Person class so name, fname and  showPersonDetails() will accessible here
 * 
 */

class EmployeeIsA extends Person {

    public int empid;

    public int getEmpid() {
        return empid;
    }

    public void setEmpid(int empid) {
        this.empid = empid;
    }

    public void showEmpDetails() {
        showPersonDetails();// this method inherit from Person class called Is-A relationship
        System.out.println("Empid:" + empid);
    }
}


/*
 * this is example of Has-A
 * here we are referencig the Person object here so name, fname and  showPersonDetails() will accessible here
 * 
 */
class EmployeeHasA {

    public int empid;
    public Person person; //Here we referencing the Person class called Has-A relationship

    public int getEmpid() {
        return empid;
    }

    public void setEmpid(int empid) {
        this.empid = empid;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
    
    public void showEmployeeHasADetails(){
        System.out.println("empid:"+this.empid);
        System.out.println("name:"+this.person.getName());
        System.out.println("name:"+this.person.getFname());
    }
}

public class IsAHasADemo {
    //Is-A demo

    Person person1 = new Person();

    public static void main(String[] args) {
        Person person1 = new Person();
        person1.setName("Ram");
        person1.setFname("Shyam");
        person1.showPersonDetails();
        
        // Is-A example
        EmployeeIsA isA = new EmployeeIsA();
        isA.setName("ABC");
        isA.setFname("XYZ");
        isA.setEmpid(100);
        isA.showEmpDetails();
        
        // Has-A example
        EmployeeHasA hasA = new EmployeeHasA();
        hasA.setEmpid(200);
        hasA.setPerson(person1);
        hasA.showEmployeeHasADetails();
    }
}