Inheritance


Inheritance

Inheritance is one of the four pillars of object oriented p. Inheritance leads to reusability and interpretability of the code. Inheritance defines “is-a” relationship. With the help of extends keyword, child class can access members of parent class.

  • Single inheritanceasd:
    If there is one base class and one derived class , then it is called single inheritance
  • Multilevel inheritance:
    If there is a base class, an intermediate base class and a sub class , this is called as multi level inheritance. Here the intermediate base class act as the base class for the sub class and the actual base class act as the base class to the intermediate base class
  • Hierarchical inheritance:
    If there is one base class and more than one derived class, then it is called as hierarchical inheritance
  • Hybrid inheritance:
    if there is a combination of more than one inheritance , then it is called as hybrid inheritance
  • Multiple inheritance (possible through interfaces):
    If there is derived class from more than one base class, then it is called Multiple inheritance. In java, Multiple Inheritance is achieved through Interfaces

The keyword used in java for performing inheritance is extends

Syntax:

childClass extends parentClass

Example No.1:

Com.knowledge2life public class Main { protected String brand = "Net programing"; public void inheritance() { System.out.println("Knowledge2life1, Knowledge2life2!"); } } class Website1 extends Main { private String Webname = "Knowledge2life3"; public static void main(String[] args) { Website1 web = new Website1(); web.inheritance(); System.out.println(web.brand + " " + web.Webname); } }

OUTPUT:

Knowledge2life1, Knowledge2life2!
Net programming Knowledge2life3

Example No.2:

Com.knowledge2life public class Main{ float income=40000; } class Website extends Main{ int bonus=10000; public static void main(String args[]){ Website p=new Website(); System.out.println("Website income is: "+p.income); System.out.println("Knowledge2life Bouns: "+p.bonus); } }

OUTPUT:

Website income is: 40000.0
Knowledge2life Bouns: 10000