Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit the fields and methods of another class. This promotes code reuse and establishes a natural hierarchy between classes. The class that inherits is called a subclass (or derived class), and the class being inherited from is called a superclass (or base class).
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
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(); // Subclass method
}
}
In this example:
Animal
is the superclass with a method eat
.Dog
is the subclass that inherits from Animal
and also has its own method bark
.Dog
object myDog
can call both the inherited eat
method and its own bark
method.