Java (programming language)
Inheritance in Java with Examples
Introduction
Inheritance is a fundamental object-oriented programming (OOP) concept that enables the creation of new classes (subclasses) based on existing ones (parent classes or superclasses). Subclassing allows you to:
- Reuse code: Subclasses inherit fields and methods from their parent class, reducing redundancy and promoting code maintainability.
- Extend functionality: Subclasses can add new fields and methods, tailoring the inherited behavior to specific needs.
- Model real-world relationships: Inheritance mirrors hierarchical relationships between objects, like “Car is a type of Vehicle.”
Key Concepts
extends
keyword: To create a subclass, useextends
followed by the parent class name:
Java
class Subclass extends Superclass {
// ...
}
- IS-A relationship: Inheritance represents an “is-a” relationship between classes. A subclass is a specialized version of its superclass.
Basic Example
Java
class Animal {
public void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
- Dog inherits the
eat()
method from Animal. - Dog adds its own
bark()
method.
Accessing Superclass Members
- Use
super
to access superclass members from a subclass:
Java
class Bird extends Animal {
public void fly() {
System.out.println("Flying...");
}
public void eat() {
super.eat(); // Call the superclass eat() method
System.out.println("Pecking for seeds...");
}
}
Method Overriding
- Subclasses can override inherited methods to provide specialized behavior:
Java
class Cat extends Animal {
@Override
public void eat() {
System.out.println("Eating cat food...");
}
}
Types of Inheritance
- Single Inheritance: A subclass inherits from one superclass.
- Multilevel Inheritance: A subclass inherits from a subclass, creating a chain of inheritance.
- Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
- Multiple Inheritance: A subclass inherits from multiple superclasses (not directly supported in Java, but achievable through interfaces).
When to Use Inheritance
- Code reuse and avoiding redundancy.
- Extending functionality of existing classes.
- Modeling real-world hierarchical relationships.
- Creating class hierarchies for better organization.
Conclusion
Inheritance is a powerful OOP tool for code organization, reusability, and extensibility. Understanding its principles and applications is essential for designing well-structured and maintainable Java applications.