Basics of Inheritance

Inheritance is the one of the most important feature of object oriented programming language. Inheritance concept came from our general life. Parent's features inherited by their children.


for example:
Say John is father of mac. John is taller then mac inherit all his father's feature and mac also will be taller like his father.




Children look like their parents, they inherit their parent's features.


Inheritance in OOP allows programmer to create a new class by using existing class.

Why we need inheritance ?

Let's say a project team working on a 2D drawing application. In this application there is a class "box" having two attributes height and width

Example


	  //file: box2d.java 
// www.jgyan.com
class box2d
{
int height;
int width;
box2d(int h,int w)
{
height=h;
width=w;
}
void print2d()
{
System.out.println("height:"+h);
System.out.println("width:"+w);
}

}

After launching their application, team intended to extends feature of their application by including 3D drawing. for that team need another class box with attributes height, width and depth .

In absence of inheritance programmer has to re-write the same code and changes.

Example :


 // file:box3d.java 
// www.jgyan.com
class box3d
{
int height;
int width;
int depth;
box3d(int h,int w,int d)
{
height=h;
width=w;
depth=d;
}
void print3d()
{
System.out.println("height:"+h);
System.out.println("width:"+w);
System.out.println("depth:"+d);
}

}
Note ! Inheritance avoid re-writing of same code in order to create new class.

Syntax :


     class <child_class> extends class <parent_class> 
{
< class-definition >
}


With inheritance new class box3d can be created without re-writing of the code.


Example :


   class A 
{
int a;
void printa(){System.out.prinltn(a);}
}

Creating a child class of class A



   class B extends A 
{
int b;
void printb()
{
System.out.prinltn(b);
} }


Above class B is child class of class A. class B inherit attributes of class A. Data members and methods of a class is known as it's feature. All data members and methods of class A is brought to class B as well.



Class B has two data members and two methods

Example :

   int a; 
int b;
void printa();
void printb();
Important ! Class A is known as parent class, super class and base class.
Class B is known as child class, sub class and derived class.