Introduce Java Inheritance and give examples
Java inheritance is a fundamental concept in object-oriented programming that allows one class (the child or subclass) to inherit the properties and behaviors (fields and methods) of another class (the parent or superclass). This mechanism promotes code reusability and establishes a hierarchical relationship between classes.
Superclass and Subclass: The class that is inherited from is called the superclass (or parent class), and the class that inherits is called the subclass (or child class).
extends
Keyword: In Java, inheritance is implemented using the extends
keyword.
Single Inheritance: Java supports single inheritance, meaning a class can inherit from only one superclass. However, a subclass can implement multiple interfaces.
Method Overriding: A subclass can provide a specific implementation of a method that is already defined in its superclass. This is known as method overriding.
Access Modifiers: The access level of the superclass members (fields and methods) determines their visibility in the subclass. For example, public
members are accessible, while private
members are not.
Here’s a simple example to illustrate inheritance in Java:
// 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.");
}
}
// Another Subclass
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
Cat cat = new Cat();
cat.eat(); // Inherited method
cat.meow(); // Cat's own method
}
}
eat()
.Animal
. It inherits the eat()
method and has its own method bark()
.Animal
. It also inherits the eat()
method and has its own method meow()
.main
method, we create instances of Dog
and Cat
, demonstrating that both subclasses can use the inherited eat()
method and their own specific methods.Java inheritance is a powerful feature that enhances the flexibility and maintainability of code. By allowing classes to inherit properties and methods from other classes, it promotes code reuse and establishes a clear relationship between different classes.