Professional Documents
Culture Documents
Inheritance is one of the key features of OOP that allows us to create a new class from an
existing class. Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the information is
made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).
Syntax
Class Super
{
//methods and filed
}
//use of extends keyword
//to perform inheritance
class Sub extends Super
{
//methods and field of Animals
//methods and fields of Dog
}
In the above example, the Sub class is created by inheriting the methods and fields from
the Super class. Here, Sub is the subclass and Super is the superclass.
class Main
{
public static void main(String[] args)
{
Dog labrador = new Dog();
labrador.name = "Tiger";
labrador.display();
labrador.eat();
}
}
1. Single Inheritance
In single inheritance, a single subclass extends from a single superclass. For example,
Syntax:
Class A
Class B extends A
In multilevel inheritance, a subclass extends from a superclass and then the same subclass
acts as a superclass for another class. For example,
Syntax:
Class A
Class B extends A
Class C extends B
Syntax:
Class A
Class B extends A
Class C extends A
Note: Java doesn’t support multiple inheritances. However, we can achieve multiple
inheritances using interface.
Sysntax:
interface A
interface B
Class C implements A, B
Sysntax:
interface A
interface B extends A
Class D implements B, C
Note:-