Java - OOP - Inheritance
Inheritance is a fundamental feature of object-oriented programming (OOP) languages, such as Java. It refers to the ability of one class to inherit the properties and methods of another class. The class that inherits properties and methods is called the subclass or child class, and the class from which it inherits is called the superclass or parent class.
Types of Inheritance:
- Single Inheritance: When a subclass inherits properties and methods of only one superclass, it is called single inheritance.
- Multilevel Inheritance: When a subclass inherits properties and methods of a parent class as well as from a parent class's parent class, it is called multilevel inheritance.
- Hierarchical Inheritance: When multiple sub-classes inherit properties and methods of the same parent class, it is called hierarchical inheritance.
- Multiple Inheritance: When a subclass inherits properties and methods from multiple superclasses, it is called multiple inheritance. However, Java does not support multiple inheritance of classes. It only supports multiple inheritance of interfaces through the use of the "implements" keyword.
// Parent class
class Animal {
public void eat() {
System.out.println("The animal is eating.");
}
}
// Child class inheriting from Animal
class Dog extends Animal {
public void bark() {
System.out.println("The dog is barking.");
}
}
// Main class
class Main {
public static void main(String[] args) {
// Creating an instance of the Dog class
Dog myDog = new Dog();
// Using methods from both the Animal and Dog class
myDog.eat(); // Output: The animal is eating.
myDog.bark(); // Output: The dog is barking.
}
}
In this example, we have a parent class Animal with a method eat(). We also have a child class Dog that inherits from Animal using the extends keyword. The Dog class also has its own method bark().
In the main() method, we create an instance of the Dog class and use methods from both the Animal and Dog class. Since Dog inherits from Animal, it has access to the eat() method. Additionally, it has its own unique method bark().