Unit 6B: Inheritance in Object-Oriented
Programming
Duration: 5 Hours
Module Overview
This module provides a comprehensive introduction to inheritance in object-oriented
programming, covering fundamental concepts, implementation techniques, and practical
applications using UML diagrams and code examples.
Learning Objectives
At the end of this unit, students shall be able to:
1. Explain the concept of inheritance
2. Implement inheritance by creating superclass and subclass relationships using the
extends keyword
3. Apply method overriding techniques
4. Design and interpret UML class diagrams showing inheritance hierarchies
Table of Contents
1. Introduction to Inheritance
2. Superclass and Subclass Relationships
3. The extends Keyword
4. Method Overriding
5. UML Class Diagrams for Inheritance
6. Practical Examples
7. Exercises
8. References
1. Introduction to Inheritance
1.1 What is Inheritance?
Inheritance is a fundamental principle of object-oriented programming that allows a class to
acquire properties and behaviors (methods) from another class. It promotes code reusability and
establishes a hierarchical relationship between classes.
1.2 Key Terminology
Superclass (Parent/Base Class): The class whose properties and methods are inherited
Subclass (Child/Derived Class): The class that inherits from the superclass
IS-A Relationship: The relationship that inheritance represents (e.g., "A Dog IS-A
Animal")
1.3 Benefits of Inheritance
Code Reusability: Avoid duplicating code across similar classes
Extensibility: Easy to add new features by extending existing classes
Maintainability: Changes in the superclass automatically reflect in subclasses
Polymorphism: Enables treating objects of different classes uniformly
2. Superclass and Subclass Relationships
2.1 Understanding the Hierarchy
In an inheritance hierarchy:
The superclass contains common attributes and methods
Subclasses inherit these common features and can add specialized features
2.2 Example Hierarchy
Animal (Superclass)
├── Dog (Subclass)
├── Cat (Subclass)
└── Bird (Subclass)
All animals share common properties (name, age) and behaviors (eat, sleep), but each subclass
has unique characteristics.
3. The extends Keyword
3.1 Syntax
The extends keyword is used to create inheritance relationships:
class Subclass extends Superclass {
// Additional attributes and methods
}
3.2 Basic Example
// Superclass
class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
[Link] = name;
[Link] = age;
}
public void eat() {
[Link](name + " is eating.");
}
public void sleep() {
[Link](name + " is sleeping.");
}
}
// Subclass
class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // Call superclass constructor
[Link] = breed;
}
public void bark() {
[Link](name + " is barking!");
}
}
3.3 The super Keyword
super() calls the superclass constructor
[Link]() calls a superclass method
Must be the first statement in the subclass constructor
4. Method Overriding
4.1 What is Method Overriding?
Method overriding occurs when a subclass provides a specific implementation of a method that
is already defined in its superclass.
4.2 Rules for Method Overriding
1. Method must have the same name as in the superclass
2. Method must have the same parameters (signature)
3. Return type must be the same or a subtype (covariant return type)
4. Access modifier cannot be more restrictive
5. Cannot override final or static methods
4.3 Using the @Override Annotation
class Animal {
public void makeSound() {
[Link]("Some generic animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
[Link]("Woof! Woof!");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
[Link]("Meow!");
}
}
4.4 Benefits of @Override
Compile-time checking to ensure you're actually overriding
Improves code readability
Prevents errors from typos
5. UML Class Diagrams for Inheritance
5.1 UML Notation for Inheritance
In UML diagrams, inheritance is represented by a solid line with a hollow arrowhead pointing
from the subclass to the superclass.
┌─────────────────┐
│ Animal │
├─────────────────┤
│ - name: String │
│ - age: int │
├─────────────────┤
│ + eat(): void │
│ + sleep(): void │
└────────△────────┘
│
│ (hollow arrow = inheritance)
│
┌────┴────┬─────────┐
│ │ │
┌───▽───┐ ┌──▽──┐ ┌───▽───┐
│ Dog │ │ Cat │ │ Bird │
├───────┤ ├─────┤ ├───────┤
│-breed │ │-color│ │-wingspan│
├───────┤ ├─────┤ ├───────┤
│+bark()│ │+meow()│ │+fly() │
└───────┘ └─────┘ └───────┘
5.2 Reading UML Inheritance Diagrams
Top boxes: Superclasses
Bottom boxes: Subclasses
Hollow arrows: Point from subclass to superclass
Attributes section: Shows fields (-) for private, (+) for public, (#) for protected
Methods section: Shows operations/behaviors
6. Practical Examples
Example 1: Vehicle Hierarchy
// Superclass
class Vehicle {
protected String brand;
protected int year;
protected double price;
public Vehicle(String brand, int year, double price) {
[Link] = brand;
[Link] = year;
[Link] = price;
}
public void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Year: " + year);
[Link]("Price: $" + price);
}
public void start() {
[Link]("Vehicle is starting...");
}
}
// Subclass 1
class Car extends Vehicle {
private int numDoors;
public Car(String brand, int year, double price, int numDoors) {
super(brand, year, price);
[Link] = numDoors;
}
@Override
public void displayInfo() {
[Link]();
[Link]("Number of doors: " + numDoors);
}
public void honk() {
[Link]("Beep beep!");
}
}
// Subclass 2
class Motorcycle extends Vehicle {
private boolean hasSidecar;
public Motorcycle(String brand, int year, double price, boolean
hasSidecar) {
super(brand, year, price);
[Link] = hasSidecar;
}
@Override
public void displayInfo() {
[Link]();
[Link]("Has sidecar: " + hasSidecar);
}
public void wheelie() {
[Link]("Performing a wheelie!");
}
}
Example 2: Employee Management System
// Superclass
abstract class Employee {
protected String name;
protected int employeeId;
protected double baseSalary;
public Employee(String name, int employeeId, double baseSalary) {
[Link] = name;
[Link] = employeeId;
[Link] = baseSalary;
}
public abstract double calculateSalary();
public void displayInfo() {
[Link]("Name: " + name);
[Link]("ID: " + employeeId);
[Link]("Salary: $" + calculateSalary());
}
}
// Subclass 1
class FullTimeEmployee extends Employee {
private double bonus;
public FullTimeEmployee(String name, int id, double salary, double bonus)
{
super(name, id, salary);
[Link] = bonus;
}
@Override
public double calculateSalary() {
return baseSalary + bonus;
}
}
// Subclass 2
class PartTimeEmployee extends Employee {
private int hoursWorked;
private double hourlyRate;
public PartTimeEmployee(String name, int id, int hours, double rate) {
super(name, id, 0);
[Link] = hours;
[Link] = rate;
}
@Override
public double calculateSalary() {
return hoursWorked * hourlyRate;
}
}
7. Exercises
Exercise 1: Basic Inheritance (Easy)
Create a class hierarchy for geometric shapes:
Create a superclass Shape with attributes color and filled
Add a method getDescription() that returns shape information
Create subclasses Circle and Rectangle that extend Shape
Circle should have a radius attribute
Rectangle should have width and height attributes
Override getDescription() in each subclass to include specific information
Exercise 2: Method Overriding (Medium)
Design a banking system:
Create a superclass BankAccount with:
o Attributes: accountNumber, balance, accountHolder
o Methods: deposit(), withdraw(), getBalance()
Create two subclasses:
o SavingsAccount: Override withdraw() to prevent withdrawals below $100
o CheckingAccount: Add an overdraft limit; override withdraw() to allow
negative balance up to the limit
Include appropriate constructors and test your implementation
Exercise 3: UML to Code (Medium)
Given the following UML diagram, implement the classes in code:
┌──────────────┐
│ Person │
├──────────────┤
│ -name: String│
│ -age: int │
├──────────────┤
│ +walk(): void│
└──────△───────┘
│
┌──────┴──────┐
│ │
┌───▽────┐ ┌────▽─────┐
│Student │ │ Teacher │
├────────┤ ├──────────┤
│-id: int│ │-subject: │
│-major: │ │ String │
│ String │ ├──────────┤
├────────┤ │+teach(): │
│+study()│ │ void │
└────────┘ └──────────┘
Exercise 4: Complex Hierarchy (Advanced)
Build a comprehensive library management system:
Create a superclass LibraryItem with common attributes (title, itemId, isAvailable)
Create subclasses:
o Book (author, ISBN, numberOfPages)
o Magazine (issueNumber, month)
o DVD (duration, director)
Implement method overriding for:
o checkOut() - different rules for each item type
o getDetails() - display specific information
o calculateLateFee() - different rates for each type
Include a Member class that can check out items
Test polymorphism by storing different items in a single array
Exercise 5: Real-World Application (Advanced)
Design an e-commerce system with the following requirements:
Create a Product superclass
Implement subclasses for Electronics, Clothing, and Food
Each should have appropriate attributes and methods
Implement a discount system using method overriding
Create a shopping cart that can hold any product type
Calculate total prices with different discount rules for each product type
Draw the UML diagram for your design
8. References
Books
1. Deitel, P., & Deitel, H. (2017). Java How to Program, Early Objects (11th ed.). Pearson.
o Chapter 9: Object-Oriented Programming: Inheritance
2. Liang, Y. D. (2018). Introduction to Java Programming and Data Structures (11th ed.).
Pearson.
o Chapter 11: Inheritance and Polymorphism
3. Sierra, K., & Bates, B. (2005). Head First Java (2nd ed.). O'Reilly Media.
o Chapter 7: Inheritance and Polymorphism
4. Bloch, J. (2018). Effective Java (3rd ed.). Addison-Wesley.
o Item 18: Favor composition over inheritance
o Item 19: Design and document for inheritance or else prohibit it
Online Resources
5. Oracle Java Documentation
o "Inheritance" tutorial:
[Link]
o "Overriding and Hiding Methods":
[Link]
6. GeeksforGeeks
o "Inheritance in Java": [Link]
7. Baeldung
o "Guide to Inheritance in Java": [Link]
8. Visual Paradigm
o "UML Class Diagram Tutorial": [Link]
unified-modeling-language/uml-class-diagram-tutorial/
UML Tools
9. Lucidchart - Online UML diagram tool: [Link]
10. [Link] - Free diagramming tool: [Link]
11. PlantUML - Text-based UML tool: [Link]
Video Tutorials
12. [Link] - "Object Oriented Programming in Java"
13. Derek Banas - YouTube series on Java OOP concepts
Assessment Criteria
Students will be evaluated on:
Understanding (30%): Ability to explain inheritance concepts clearly
Implementation (40%): Correct use of extends keyword and method overriding
UML Design (20%): Accurate creation and interpretation of class diagrams
Code Quality (10%): Proper naming conventions, documentation, and organization
Additional Notes
Practice drawing UML diagrams by hand before using software tools
Always consider whether inheritance is appropriate (IS-A relationship) or if composition
would be better (HAS-A relationship)
Remember that Java supports single inheritance only (one direct superclass)
Use protected access modifier when you want subclasses to access superclass members
directly
This module is designed for a 5-hour learning session with a mix of lecture, examples, and
hands-on practice.