info@tutsfinder.in



Inheritance

Inheritance is one of the features of OOP where one class acquires the properties of another class.

Inheritance represents IS-A relationship and used for reusability of code.

Superclass is the class from which class is derived. Super class is also called parent class or base class.

• A class is derived from the superclass is called as the child class or derived class.

• Methods and variables must be in public or protected except private.

extends keyword is used to inherit the class.

Types of Inheritance:

1. Single Inheritance - When a class inherited by another class is known as single inheritance.

For Example - car class inherits vehicle class.


single inheritance

2. Multi-level Inheritance - There is a chain of classes where class A inherits class B and class B is also inherited by another class C.

For Example - BMW inherits the car class and car inherits the vehicle class.


multilevel inheritance

3. Mutiple Inheritance - When properties of more than one parent is inherited by another class then this is known as multiple inheritance.

But java does not support multiple inheritance because it creates ambiguity problem.

To overcome this problem, there is a concept in java i.e. Interface. Later we will learn about it .


multiple inheritance

4. Hierarchical Inheritance- When more than one class acquires the property of a single class then is called as hierarchical inheritance.

For Example - Car and bike class inherits the vehicle class.


Hierarchical inheritance

5. Hybrid Inheritance - It is a comination of more than one type of inheritance.

When class A is inherited by class B and C, and class C is inherited by class D.


Hybrid inheritance


Example to show class can be extended.

class Vehicle
{
// member declarations
}
class Car extends Vehicle
{
// inherit accessible members from Vehicle
// own member declarations
}




Program to show how inheritance works in java.

class Vehicle{

void run(){
System.out.println("Vehicle is running");
}
}
class Car extends Vehicle{
void stop(){
System.out.println("Car is stop");
}
}
class Main{
public static void main(String[] args){
Car obj=new Car();
obj.run();
obj.stop();
}
}


This program is also a example of Single Inheritance where Vehicle is parent class and Car is child class