Inheritance
in JavaInheritance is one of the fundamental concepts of Object-Oriented Programming (OOP) that allows a new class (subclass or derived class) to inherit properties and behaviors (fields and methods) from an existing class (superclass or base class). This promotes code reusability and establishes a natural hierarchy between classes.
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 dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Method of Dog class
}
}
This animal eats food.
The dog barks.
In this example, Dog
is a subclass that inherits the eat
method from the Animal
superclass.
A class inherits from only one superclass.
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
A class inherits from a superclass, and another class inherits from that subclass, forming a chain.