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
► For Method Overriding
► For Code Reusability.
Terms used in Inheritance
► Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
► Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Java Inheritance Example
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000; Output:
Programmer salary is:40000.0
public static void main(String args[]){ Bonus of programmer is:10000
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
} }
Types of inheritance in java
► 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?
}
}