Processes of acquiring properties and behaviour from one class to another class is called inheritance. Inheritance can be achieved by using ‘extends’ keyword. The one who is providing property are called parent, base and super class and the one who acquire property are called child, derived and sub class.
To understand the Inheritance concept, now see the application with out inheritance:
class A
{ void m1();
void m2();
}
class B
{ void m1();
void m2();
void m3();
void m4();
}
class C
{ void m1();
void m2();
void m3();
void m4();
void m5();
void m6();
}
The problems here is, classes of a Application contain duplication's of same methods and length of the coding increases with this approach.
These problems can be avoided by using inheritance. Now see the same above application with inheritance as below examples:
Example 1:
class A
{ void m1(){}
void m2(){}
}
class B extends A //class B four methods m1, m2, m3 and m4.
{ void m3(){}
void m4(){}
}
class C extends B // class C contains six methods m1, m2, m3, m4, m5 and m6.
{ void m5(){}
void m6(){}
}
The ‘extends’ keyword is used to acquire all the properties of the that specific class.
Example 2:
class A extends object class
{ void m1(){}
void m2(){}
}
class B extends C //class B six methods m1, m2, m3, m5 and m6.
{ void m3(){}
void m4()
}
class C extends A // class C contains four methods m1, m2, m5 and m6.
{ void m5(){}
void m6(){}
}
Example 3:
class A
{ void m1(){}
void m2(){}
}
class B
{ void m3(){}
void m4(){}
}
class C extends A //class contain four methods m1,m2,m5 and m6.
{ void m5(){}
void m6(){}
}
Example 4: (This type of inheritance is not supported in java)
class A
{ void m1(){}
void m2(){}
}
class B
{ void m3(){}
void m4(){}
}
class C extends A,B //This inheritance is not supported in java.
{ void m5(){}
void m6(){}
}
If you want that your class not be inherited then declare your class with ‘final’ keyword then child class creation is not possible.
Example:
class A
{
}
final class B extends A
{
}
class C extends B
{
}
Output:
inheritance_exp.java:7: error: cannot inherit from final B
class C extends B
^
1 error
Example:
class A
{
}
final class B extends A
{
}
class C extends B
{
}
Output:
inheritance_exp.java:7: error: cannot inherit from final B
class C extends B
^
1 error