Module 7: Inheritance and Polymorphism
7.1 Introduction
Inheritance and polymorphism are key pillars of Object-Oriented Programming (OOP). They enable code reuse, extensibility, and flexibility by building hierarchical relationships between classes.
7.2 What Is Inheritance?
Inheritance allows one class to acquire the properties and methods of another class. The derived class is known as a subclass (or child class), and the original is the superclass (or parent class).
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 d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
}
}
Output:
This animal eats food.
The dog barks.
7.3 The super Keyword
The super keyword is used to refer to the parent class. It can call the parent constructor or access parent methods.
class Animal {
Animal() {
System.out.println("Animal created");
}
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
Dog() {
super(); // Calls Animal constructor
System.out.println("Dog created");
}
void eat() {
super.eat(); // Calls parent method
System.out.println("Dog eats bones");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
}
}
Output:
Animal created
Dog created
Eating...
Dog eats bones
7.4 Types of Inheritance in Java
- Single Inheritance: One subclass extends one superclass.
- Multilevel Inheritance: A subclass is derived from another subclass.
- Hierarchical Inheritance: Multiple subclasses share a single superclass.
Java doesn’t support multiple inheritance using classes (to avoid ambiguity), but it can be achieved using interfaces.
7.5 Method Overriding
When a subclass defines a method with the same name and signature as its superclass, it overrides the superclass method.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Cat();
a.makeSound(); // Calls overridden method in Cat
}
}
Output:
Meow
7.6 The @Override Annotation
The @Override annotation ensures that the method is correctly overriding a superclass method. It helps prevent typos or signature mismatches.
@Override
void makeSound() {
System.out.println("Bark");
}
7.7 Polymorphism
Polymorphism means “many forms.” It allows one interface to be used for different data types or objects.
In Java, polymorphism is mainly achieved through method overriding and dynamic method dispatch.
Example:
class Animal {
void speak() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void speak() {
System.out.println("Bark");
}
}
class Cat extends Animal {
void speak() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.speak();
a = new Cat();
a.speak();
}
}
Output:
Bark
Meow
7.8 The final Keyword
finalvariable – cannot be reassigned.finalmethod – cannot be overridden.finalclass – cannot be subclassed.
Example:
final class Vehicle {
void run() {
System.out.println("Vehicle running");
}
}
// class Car extends Vehicle {} // Error: cannot inherit from final class
7.9 The Object Class
Every class in Java implicitly extends the Object class. Common methods include:
toString()– returns string representationequals()– compares objectshashCode()– returns unique hash value
public class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
public String toString() {
return name + " (" + age + ")";
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Liam", 30);
System.out.println(p.toString());
}
}
Output:
Liam (30)
7.10 Practice Exercises
- Animal Hierarchy: Create an
Animalsuperclass and subclasses likeDog,Cat, andBirdwith overriddenspeak()methods. - Vehicle Inheritance: Implement a
Vehiclesuperclass and subclasses likeCarandTruckthat override adrive()method. - super Keyword: Use
superto call the parent constructor and display initialization order. - Polymorphism Demo: Create an array of
Animalobjects and callspeak()on each to demonstrate polymorphism. - Final Class: Try to extend a
finalclass to observe compile-time error.
7.11 Summary
- Inheritance allows a subclass to reuse fields and methods of a superclass.
- Use
superto access parent methods and constructors. - Overriding enables polymorphism by redefining parent behavior.
- The
@Overrideannotation ensures correct overriding. - Polymorphism allows one interface to represent multiple behaviors.