In Java, inheritance is a fundamental feature of object-oriented programming (OOP) that allows one class to inherit the properties and behaviors (methods and fields) of another class. This promotes code reuse and enables the creation of hierarchical relationships between classes. Here's an overview of Java inheritance:
Superclass and Subclass:
Inheritance involves two types of classes: the superclass (also known as the parent class) and the subclass (also known as the child class).
The subclass inherits attributes and methods from its superclass.
The subclass can add its own attributes and methods, and it can also override methods inherited from the superclass.
Syntax for Inheritance:
In Java, inheritance is declared using the extends keyword.
class Superclass {
// Superclass members
}
class Subclass extends Superclass {
// Subclass members
}
Example of Inheritance:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: Animal is eating
dog.bark(); // Output: Dog is barking
}
}
Types of Inheritance:
Single Inheritance: A subclass inherits from only one superclass.
Multilevel Inheritance: A subclass is also a superclass for another subclass.
Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
Multiple Inheritance (not supported in Java): A subclass inherits from multiple superclasses. Java does not support this directly to avoid ambiguity, but it supports interface implementation to achieve a similar effect.
Access Modifiers in Inheritance:
Subclasses inherit all accessible members (fields and methods) from their superclass.
Access modifiers (public, protected, default, private) control the visibility of inherited members.
In general, subclasses can access public and protected members of the superclass.
Method Overriding:
Subclasses can override methods inherited from their superclass to provide specialized behavior.
The overridden method must have the same name, return type, and parameters as the method in the superclass.
Use the @Override annotation to indicate that a method is intended to override a superclass method (optional but recommended).
Summary:
Inheritance is a fundamental OOP concept in Java that allows one class to inherit properties and behaviors from another class.
It enables code reuse, hierarchical relationships, and specialization of classes.
Java supports single, multilevel, and hierarchical inheritance but does not support multiple inheritance directly.
Access modifiers control the visibility of inherited members, and method overriding allows subclasses to provide specialized implementations of inherited methods.