INHERITANCE
Its just simply say childs can use or access their parent property. It means a child class object can access the super class methods.
There is a important key word used in this concept is extends.
Ex: class child extends father {}
It represents IS-A relationship
ex:Dhoni IS-A Cricketer,
R15 IS-A Bike.
Uses are code reusability, method overriding.
Types of Inheritance
• single inheritance
• mutilevel inheritance
• hierarchical inheritance
• multiple inheritance
• hybrid iheritance
single inheitance
it has single parent class and single child class.
class bird{
void sound(){
System.out.println();
}
void color(){
System.out.println();
}
void eatinghabit(){
System.out.println();
}
public static void main (String [] args){
bird b=new bird();
b.color();
b.sound();
b.eatinghabit();
}
multilevel inheritance
it has chain of inheritance like one below one.
class bird{
void sound(){
System.out.println();
}
}
class bigbird extend bird{
void height(){
System.out.println();
}
}
class peacock extends bigbird{
void color(){
System.out.println();
}
}
class ExamineInheritance{
public static void main(String [] args){
ExamineInheritance EI=new Examine Inheritance();
EI.color();
EI.height();
}
}
Hierarchical inheritance
It shows single parent and multiple child concept.
class bird{
void sound(){
System.out.println();
}
}
class chicken extends bird{
void walk(){
System.out.println(“only walk”);
}
}
class parrot extends bird{
void fly(){
System.out.println(“can walk and fly ”);
}
}
class ExamineInheritance{
public static void main(String [] args){
ExamineInheritance EI=new Examine Inheritance();
EI.walk();
EI.fly();
}
}
Mutiple inheritance
java dosen’t support multiple inheritance through classes. Its only achieved by interfaces.
Multiple inheritance shows a single child using more than one parents and the disadvantage is
suppose the child want to execute function which is common to both parents the child decide which
parent cause dynamic problem.
We can see multiple inheritance in detail in future blogs.
Hybrid Inheritance
This is nothing but the combination of previously shown inheritances of single and hierarchical.
It combine both concepts just shown below.
Single child and multiple child
grandfather
|
(single inheritance) |
_______________________son_____________
| |
| (multiple inheritance) |
grandson granddaughter
this example show single and multiple child concept with real life relations.
public class Grandfather{
public void print (){
System.out.println(“kumar”);
}
}
public class Son extends Grandfather{
public void print (){
System.out.println(“ram”);
}
}
public class Grandson extends Son{
public void print (){
System.out.println(“raj”);
public class Granddaughter extends Son{
public void print (){
System.out.println(“diya”);
}
public static void main(String [] args){
Granddaughter gd=new Granddaughter();
gd.print();
}
}
RESULT :
diya }
}
now you all know about inheritanc after this we gonna see polymorphism.