Q. What is inheritance? Explain different types of Inheritance with example.
Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports concept of hierarchical classification. The concept of Inheritance provides the idea of reusability. We can add up additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes.
Inheritance allows the programmer to reuse a class that is almost but not exactly the programmer needs.
The derived class is known as the sub class. For Example Grandfather is a very good dancer, and father is avery good singer, the child can have property of being a very good dancer but by inheritance we can say that he is a very good dancer as well as a singer.
Example :
Class Room
{
int length;
int breadth;
Room ( int x, int y)
{
length = x;
breadth = y;
}
int area()
{
return ( length * breadth);
}}
class bedroom extends Room
{
int height;
bedroom ( int x , int y , int z )
{
super ( x, y) // pass values to super class )
height = z;
}
int volume ()
{
return ( length * breadth * height );
}
}
Class inherit
public static void mein ( String args[])
{
bedroom room 1 = new bedroom(14, 12, 10 );
int area1 = room1.area();//super class method
int volume1 = room1.volume(); // baseclass method
System.out.println( " Area1 = " + area);
System.out.println("volume = " + volume );
}
1. Single Inheritance ( Only one Super Class )
2. Multiple Inheritance (Serveral Super Classes )
3. Hierarchical Inheritance ( One Super Class and many sub classes )
4. Multi Level Inheritance ( Derived from a Derived class )