Difference between ‘is-a’ relationship and ‘has-a’ relationship in java

The following table shows the main differences between 'is - a' relationship and 'has - a' relationship in java. 


‘is – a’ relationship

‘has – a’ relationship
1
The ‘is – a’ relationship is expressed with Inheritance.

The ‘has – a’ relationship is expressed with Composition.

2
Class Inheritance.

Object Composition.
3
Inheritance uses extend keyword

Composition uses new keyword.
4
Inheritance is uni – directional. For example House is a Building. But Building is not House.

Composition is used when House has a Bathroom. It is incorrect to say House is a bathroom. Which simply uses instance variable that refer to the other object
5

Is a [House is a Building]
class Building
{
 ……….
}

class House extends Building
{
………..
}

Has a [House has a Bathroom]
class Bathroom
{
 …………
}

class House
{
  Bathroom room=new Bathroom();
  ………..
}
6
Example:
class A
{
  void print()
  {
    System.out.println(“ Content from Class A”);
  }
}

class B extends A
{
  B()
  {
    print();
  }
}

public class test
{
  public static void main(String args[])
  {
    B obj=new B();
 }
}



C:\> java test
Content from Class A

Example:
class A
{
  void print()
  {
    System.out.println(“ Content from Class A”);
  }
}

class B
{
  A a1;
  B()
  {
     a1 = new A();
     a1.print();
  }
}

public class test
{
  Public static void main(String args[])
  {
     B obj=new B();
 }
}

C:\> java test
Content from Class A