DEV Community

Deva I
Deva I

Posted on

Inheritence in Java

Inheritance in Java allows one class to acquire the properties (fields) and behaviors (methods) of another class.

Superclass(Parent/Base Class): The existing class.

Subclass (Child/Derived Class): The new class that inherits features from the superclass. It can reuse, modify, or add its own variables and methods.

extends Keyword: The Java keyword used to create a subclass.

Types of Inheritance

  • Single Inheritance : A subclass inherits from exactly one superclass.

EX: Class AClass B

  • Multilevel Inheritance : A class inherits from a subclass, creating a chain of inheritance.

EX: Class AClass BClass C

  • Hierarchical Inheritance : Multiple subclasses inherit from the same single superclass.

EX: Class AClass B & Class C

Example Code

// Superclass(Parent/Base Class)

package thanjavur;
public class RajaRajaChola
{
public void abdication(){
System.out.println("The king gives the throne to Prince");

}
}
Enter fullscreen mode Exit fullscreen mode
// Subclass (Child/Derived Class)

package gangaikondaCholapuram;
import thanjavur.RajaRajaChola;
public class RajendraChola extends RajaRajaChola
{
public static void main(String[] args)
{
RajendraChola coronation = new RajendraChola();
coronation.abdication();

}
}
Enter fullscreen mode Exit fullscreen mode

Output

Top comments (0)