DEV Community

KIRAN RAJ
KIRAN RAJ

Posted on

Today topic in payilagam types of inheritance in java

Understanding Inheritance in Java
Inheritance is a fundamental concept in Java that allows one class to inherit the properties and behavior of another class. In this blog, we'll explore the basics of inheritance, its types, and how it's implemented in Java.

What is Inheritance?
Inheritance in Java is a mechanism where a subclass or child class inherits the fields and methods of a superclass or parent class. The extends keyword is used to establish this relationship between the child class and the parent class.

Types of Inheritance
There are five types of inheritance in Java:

  1. Single Inheritance: A subclass is derived from only one superclass. It inherits the properties and behavior of a single-parent class.
  2. Multilevel Inheritance: A derived class inherits a base class, and the derived class acts as a base class for other classes.
  3. Hierarchical Inheritance: More than one subclass is inherited from a single base class. For example, cars and buses are both vehicles.
  4. Multiple Inheritance: Not directly supported in Java through classes. However, it can be achieved through interfaces, where one class can implement multiple interfaces.
  5. Hybrid Inheritance: A mix of two or more other inheritances. It can be achieved in Java through interfaces.

Implementing Inheritance in Java
To implement inheritance in Java, you use the extends keyword. Here's a simple example:
// Parent class
class Vehicle {
void honk() {
System.out.println("Honking!");
}
}

// Child class
class Car extends Vehicle {
void accelerate() {
System.out.println("Accelerating!");
}
}

public class Main {
public static void main(String[] args) {
Car car = new Car();
car.honk(); // Inherited from Vehicle
car.accelerate(); // Specific to Car
}
}
Key Takeaways

  • Inheritance allows a subclass to inherit the properties and behavior of a superclass.
  • The extends keyword is used to establish the relationship between the child class and the parent class.
  • Java supports single, multilevel, hierarchical, and hybrid inheritance (through interfaces).

By understanding inheritance and its types, you can design more efficient and reusable code in Java.

Top comments (0)