IS-A Relationship

IS-A Relationship
  • IS-A relationship also known as β€˜inheritance’.
  • By using extends keyword we can implement inheritance.
  • The main advantage is reusability.

Note

Parent class reference can be used to hold child class object but by using that reference we are not allowed to call child class specific methods.

class P {
   m1() {
   }
   m2() {
   }
}

class C extends P {
   m3() {
   }
}

class Test {
   public static void main(String arg[]) {
      P p1 = new P();
      p1.m1();
      p1.m2();
      p1.m3(); //C.E: Child class methods are not available to the parent class.

      C c1 = new C();
      c1.m1();
      c1.m2();
      c2.m3(); // Fine
   
      P p2 = new C();
      p2.m1();
      p2.m2();
      p2.m3(); //C.E: By using parent class reference we can’t call child class specific method
      
      C c4 = new P(); //C.E: Child class reference can’t be used to hold parent class object.
   }
}

Note

  • Java won’t provide support for multiple inheritance but through interfaces it is possible.
class A extends B,C {
   -----------
   -----------
} // C.E

interface A extends B,C {

   -----------
   -----------
} // Fine
  • Cycle inheritance is not allowed in java
class A extends B {
}

class B extends A {
}

class A extends A {
}

 Above both gives compile time error saying cyclic inheritance involving

IS-A Relationship


Scroll to top