Types of inheritance in java
There
are three types of inheritance in java:
single, multilevel and hierarchical.
1.
Single Inheritance
In single inheritance,
subclasses inherit the features of one superclass. In image below, the class A
serves as a base class for the derived class B.
single inheritance |
Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
Barking…..
Eating……
1.
Multilevel Inheritance
In Multilevel Inheritance, a derived class will be
inheriting a base class and as well as the derived class also act as the base
class to other class. In below image, the class A serves as a base class for
the derived class B, which in turn serves as a base class for the derived class
C. In Java, a class cannot directly access the grandparent’s members.
multilevel inheritance |
Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
} }
Output:
Weeping…..
Eating…..
Braking…..
1.
Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one sub class.In below image, the class A
serves as a base class for the derived class B,C and D.
herarchical inheritance |
Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
} }
Output:
Meowing……
Eating……….
No comments:
Post a Comment