Inheritance

Inheritance is another important feature of object oriented programming, it provides the feature of code reusability, where one class inherits the features of another class, reducing code redundancy(duplication).

Inheritance support two type of relationship
  • IS-A relationship - used when you want to use all the features(variable and methods) of the base class.
  • Has-A relationship - used when you want to use only some features of the base class.
IS_A relationship is further divided
  • Single level Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
NOTE :
Java does not support Multiple Inheritance. Multiple Inheritance can be achieved in java through the implementation of Interfaces.
single inheritence example
multilevel inheritence
Hierarchical inheritence

Difference between IS-A and HAS-A relationship
IS-A HAS-A
Used to create a parent child relationship. IS-A is based on class inheritance or interface. HAS-A ralationship is based on usage, rather than inheritance.
Example: BMW IS-A Car, Horse IS-A Animal, AutoLoan IS-A Loan. Example: Horse HAS-A Halter, Customer HAS-A Loan.
IS-A can be used by extends or implements keyword. HAS-A can be used by making an object of the other class part of your class.
Advantage of IS-A
  • To promote code reuseability, so code redundancy is reduced.
  • Promotes Polymorphism.
Advantage of HAS-A
  • Can work on other class instance variables & methods without inheriting that class.
  • Promotes Encapsulation
NOTE :
  • We cannot make a single program with out inheritance in java, because every class inherit java.lang.Object class.
  • Java is a package centric language, and so implicitly helps in good organization and name scoping.