8 Inheritance
8 Inheritance
Inheritance in Java
► Is a mechanism in which one object acquires all the properties and behaviors of a
parent object.
► Idea behind inheritance in Java is that you can create new classes that are built
upon existing classes.
► When you inherit from an existing class, you can reuse methods and fields of the
parent class.
► Moreover, we can add new methods and fields in your current class also.
Why use inheritance in java
► Sub Class/Child Class: Subclass is a class which inherits the other class.
► Single Inheritance
► Multilevel inheritance
► Hierarchical inheritance
► Multiple Inheritance
► Hybrid inheritance
Single Inheritance
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(); Output:
Barking…
d.bark();
eating...
d.eat();
}}
Multilevel Inheritance Example
class Animal{ class TestInheritance2{
void eat() public static void main(String args[]){
{ System.out.println("eating..."); } BabyDog d=new BabyDog();
} d.weep();
class Dog extends Animal{ d.bark();
void bark() d.eat();
{ System.out.println("barking..."); } }}
}
class BabyDog extends Dog{ weeping...
void weep() barking...
eating...
{ System.out.println("weeping..."); }
}
Hierarchical Inheritance Example
class Animal{ class TestInheritance3{
void eat() public static void main(String args[]){
{ System.out.println("eating..."); }
Cat c=new Cat();
}
c.meow();
class Dog extends Animal{
c.eat();
void bark()
//c.bark();
{ System.out.println("barking..."); }
}}
}
class Cat extends Animal{
Output:
void meow()
meowing...
{ System.out.println("meowing..."); } eating...
}
Multiple inheritance
► One subclass extends more than one super class
Class A Class B
Class C
Why multiple inheritance is not supported in java?
class A{
void msg() {System.out.println("Hello"); }
}
class B{
void msg() {System.out.println("Welcome");}
}
class C extends A,B
{
public static void main(String args[])
{
C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
}
}