Inheritance is a cornerstone of object-oriented programming in Java. It allows a class to inherit properties and methods from another class, promoting code reuse and establishing a hierarchical relationship between classes.
In Java, inheritance is implemented using the extends
keyword. The class that inherits is called the subclass (or child class), while the class being inherited from is the superclass (or parent class).
class Subclass extends Superclass {
// Subclass members
}
Through inheritance, the subclass automatically gains access to all non-private members of the superclass. This mechanism facilitates the creation of specialized classes based on more general ones.
super
Keyword: Used to call the superclass constructor or access superclass members.Let's look at a simple example demonstrating inheritance in Java:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Dog's own method
}
}
In this example, Dog
inherits the eat()
method from Animal
and adds its own bark()
method.
toString()
method for meaningful object representations.To fully grasp inheritance in Java, it's beneficial to understand these related topics:
Mastering inheritance is crucial for effective object-oriented design in Java. It provides a powerful mechanism for creating flexible and maintainable code structures.