Java Inheritance Explained
Introduction to Java Inheritance
Inheritance is a fundamental concept in Java and object-oriented programming (OOP). It allows a new class to acquire the properties and behaviors of an existing class.
This tutorial explains how inheritance works in Java, why it is useful, and how to implement it effectively with practical examples.
Inheritance enables code reuse and establishes a natural hierarchy between classes.
What is Inheritance?
Inheritance lets one class inherit fields and methods from another class. The class that inherits is called the subclass or child class, and the class being inherited from is the superclass or parent class.
This mechanism promotes code reuse and helps organize code logically by creating a class hierarchy.
- Subclass inherits accessible fields and methods from superclass.
- Subclass can add new fields and methods or override existing ones.
- Supports the 'is-a' relationship (e.g., a Dog is an Animal).
Syntax of Inheritance in Java
In Java, inheritance is implemented using the 'extends' keyword. A subclass extends a superclass to inherit its members.
The basic syntax is: `class Subclass extends Superclass { }`.
- Only single inheritance is allowed for classes (a class can extend only one class).
- Interfaces support multiple inheritance of type.
Types of Inheritance
Java supports several types of inheritance to model different relationships between classes.
- Single Inheritance: One subclass inherits from one superclass.
- Multilevel Inheritance: A subclass inherits from a class which itself is a subclass.
- Hierarchical Inheritance: Multiple subclasses inherit from one superclass.
| Type | Description | Example |
|---|---|---|
| Single | One subclass inherits from one superclass | class Dog extends Animal {} |
| Multilevel | Subclass inherits from a subclass | class Puppy extends Dog {} |
| Hierarchical | Multiple subclasses inherit from one superclass | class Cat extends Animal {}, class Dog extends Animal {} |
Access Control and Inheritance
Access modifiers affect what members a subclass can inherit and access.
Understanding these modifiers is key to designing secure and maintainable inheritance hierarchies.
- public members are accessible everywhere.
- protected members are accessible in the same package and subclasses.
- default (package-private) members are accessible only within the same package.
- private members are not inherited.
Method Overriding and Polymorphism
Subclasses can override methods of the superclass to provide specific implementations.
This enables polymorphism, where a superclass reference can point to subclass objects and invoke overridden methods dynamically.
- Use @Override annotation to indicate method overriding.
- Overridden methods must have the same signature and compatible return type.
- Superclass methods can be called using super keyword.
Example: Implementing Inheritance in Java
Let's look at a simple example demonstrating inheritance, method overriding, and polymorphism.
Examples
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
myAnimal.sound();
Dog myDog = new Dog();
myDog.sound();
Animal polyAnimal = new Dog();
polyAnimal.sound(); // Demonstrates polymorphism
}
}This example defines a superclass Animal and a subclass Dog that overrides the sound() method. It shows how inheritance and polymorphism work in Java.
Best Practices
- Use inheritance to model 'is-a' relationships only.
- Prefer composition over inheritance when possible to reduce tight coupling.
- Always use @Override annotation when overriding methods.
- Keep superclass methods general and subclasses specific.
- Avoid deep inheritance hierarchies to maintain code clarity.
Common Mistakes
- Using inheritance to reuse code without a logical 'is-a' relationship.
- Overriding methods without @Override annotation leading to subtle bugs.
- Trying to inherit from multiple classes (Java does not support multiple class inheritance).
- Accessing private superclass members directly in subclasses.
- Creating deep inheritance chains that are hard to maintain.
Hands-on Exercise
Create a Vehicle Inheritance Hierarchy
Define a superclass Vehicle with a method move(). Create subclasses Car and Bicycle that override move() with specific behavior. Instantiate and test polymorphism.
Expected output: Output showing Vehicle moving, Car moving, and Bicycle moving with overridden messages.
Hint: Use extends keyword and override move() method in subclasses.
Interview Questions
What is inheritance in Java?
InterviewInheritance is an OOP concept where a new class (subclass) inherits properties and behaviors from an existing class (superclass), promoting code reuse and hierarchical classification.
Can a Java class inherit from multiple classes?
InterviewNo, Java supports single inheritance for classes. However, a class can implement multiple interfaces to achieve multiple inheritance of type.
What is method overriding?
InterviewMethod overriding occurs when a subclass provides a specific implementation for a method already defined in its superclass, allowing runtime polymorphism.
Summary
Inheritance is a core feature of Java's object-oriented programming that enables classes to inherit properties and methods from other classes.
It promotes code reuse, logical class hierarchies, and polymorphism through method overriding.
Understanding inheritance, access control, and best practices is essential for designing robust Java applications.
FAQ
What keyword is used to inherit a class in Java?
The 'extends' keyword is used for a class to inherit from another class.
Can a subclass access private members of its superclass?
No, private members are not accessible or inherited by subclasses.
What is the difference between method overloading and overriding?
Method overloading is defining multiple methods with the same name but different parameters in the same class. Overriding is redefining a superclass method in a subclass with the same signature.
