Classes

Java Inheritance

Class Inheritance

Java inheritance uses extends for single inheritance.

What is Inheritance in Java?

Inheritance in Java is a mechanism where one class acquires the properties (fields) and behaviors (methods) of another class. It allows for a hierarchical classification and promotes reusability of code. The class that inherits the properties of another is called the subclass or derived class, and the class whose properties are inherited is known as the superclass or base class.

How to Implement Inheritance in Java

In Java, inheritance is implemented using the extends keyword. A class that is derived from another class can access its public and protected members. However, private members are not accessible directly and can be accessed only through public or protected methods of the superclass.

Types of Inheritance in Java

Java supports different types of inheritance:

  • Single Inheritance: A class inherits from only one superclass.
  • Multilevel Inheritance: A class is derived from another derived class.
  • Hierarchical Inheritance: Multiple classes inherit from a single superclass.

Note: Java does not support multiple inheritance with classes to avoid complexity and simplify the design. This can be achieved using interfaces.

Advantages of Inheritance

Inheritance provides several benefits:

  • Code Reusability: Methods and fields of the superclass can be reused in the subclass.
  • Method Overriding: Subclass can provide specific implementation for methods that are already defined in its superclass.
  • Polymorphism: It enhances polymorphism, allowing for dynamic method dispatch.

Method Overriding

In Java, a subclass can override a method of its superclass to provide a specific implementation. Method overriding is a key feature of inheritance that supports runtime polymorphism.

Previous
Interfaces