
In Java, inheritance is a fundamental concept of object-oriented programming (OOP) that allows a class to inherit properties and behaviors (i.e., fields and methods) from another class. The class that inherits from another class is known as the subclass or derived class, and the class being inherited from is called the superclass or base class. Inheritance creates an “is-a” relationship between classes, where a subclass is a specialized version of the superclass.
Inheritance is denoted in Java using the extends keyword. Here’s the basic syntax for defining a subclass that inherits from a superclass:
class Superclass {
// Fields and methods of the superclass
}
class Subclass extends Superclass {
// Fields and methods specific to the subclass
}
Key points about inheritance in Java:
- Code Reusability: Inheritance promotes code reusability by allowing the subclass to inherit the properties and behaviors of the superclass. This means that the common features can be defined once in the superclass and reused in multiple subclasses.
- Access Modifiers: The members (fields and methods) of a superclass may have different access modifiers (e.g., public, protected, private). The subclass can access the public and protected members of the superclass. However, the private members are not directly accessible in the subclass.
- Single Inheritance: Java supports single inheritance, which means a class can only inherit from one superclass. Unlike some other programming languages that support multiple inheritance, Java avoids complexities related to the “diamond problem.”
- Object Class: In Java, if a class doesn’t explicitly extend another class, it implicitly inherits from the Object class, which is the root of the class hierarchy in Java.
- Overriding Methods: Subclasses can override methods from the superclass to provide their own implementation. This allows customization of behavior while maintaining the same method signature.
Example of inheritance in Java:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
In this example, the Dog class is a subclass of the Animal class. The Dog class inherits the makeSound() method from the Animal class but provides its own implementation to override the behavior of the superclass method. When you create an instance of Dog and call makeSound(), it will print “Dog barks” instead of “Animal makes a sound.”