CACS204 Object Oriented Programming in Java

Object Oriented Programming in JavaUnit 514 min read

Inheritance in Java: Extends, Types, Abstract Classes & Interfaces

Unit 5 of Object Oriented Programming in Java covers inheritance (single, multilevel, hierarchical, multiple), the extends keyword, abstract classes, interfaces, and method overriding. Learn how to reuse code, enforce design rules, and model real-world hierarchies with clear examples, visual traces, and exam-focused ti

TAKEAWAYS:

  • Inheritance lets a child class reuse and extend a parent class using extends, saving time and reducing code duplication.
  • Java supports four types of inheritance: single, multilevel, hierarchical, and hybrid (via interfaces).
  • Abstract classes use abstract methods to define a contract without full implementation, forcing subclasses to provide logic.
  • Interfaces enforce multiple inheritance of type (but not implementation) and are used for APIs like Comparable or Runnable.
  • Method overriding replaces a parent’s method in a child class, enabling polymorphism (one interface, many behaviors).
  • Keywords like super(), @Override, and final control inheritance behavior and prevent unintended modifications.

Core Concepts of Inheritance

1. What is Inheritance?

Inheritance is an OOP principle where a child class (subclass) inherits properties and behaviors (fields/methods) from a parent class (superclass). It promotes code reusability and establishes an "is-a" relationship.

Example in Real Life:

  • A Dog is-a Mammal is-a Animal.
  • In Java: Dog extends Mammal extends Animal.
class Animal {
    void eat() { System.out.println("Eating..."); }
}

class Mammal extends Animal {
    void breathe() { System.out.println("Breathing..."); }
}

class Dog extends Mammal {
    void bark() { System.out.println("Barking..."); }
}

Visual: Class Hierarchy

AnimalMammalDog
Hierarchy: Animal → Mammal → Dog (solid line = 'extends')

2. Types of Inheritance in Java

Java supports four types, but multiple inheritance of classes is not allowed (to avoid ambiguity). Instead, use interfaces.

SingleMultilevelHierarchicalMultipleHybrid
Java inheritance types (multiple inheritance via interfaces only)
Type Description Example
Single One subclass inherits from one superclass. class Car extends Vehicle
Multilevel Chain of inheritance (grandparent → parent → child). class Bike extends Vehicle extends Object
Hierarchical Multiple subclasses inherit from one superclass. class Dog extends Animal, class Cat extends Animal
Hybrid Combination of two or more types (achieved via interfaces). class Smartphone implements Camera, MusicPlayer

Why No Multiple Inheritance of Classes?

// ERROR: Java does not allow this!
class A { void show() {} }
class B { void show() {} }
class C extends A, B {} // Compile-time error: Ambiguous method call.

Workaround: Use Interfaces

interface A { void show(); }
interface B { void show(); }
class C implements A, B {
    public void show() { System.out.println("Resolved ambiguity"); }
}

3. The extends Keyword

  • Used to inherit from a superclass.
  • Syntax: class ChildClass extends ParentClass { ... }
  • Key Points:
    • Child class inherits all non-private members (fields/methods) of the parent.
    • Can override or add new methods.
    • Uses super to call parent class methods/constructors.

Example: Bank Account Hierarchy

class Account {
    private String accountNumber;
    Account(String accNum) { this.accountNumber = accNum; }
    void display() { System.out.println("Account: " + accountNumber); }
}

class SavingsAccount extends Account {
    private double interestRate;
    SavingsAccount(String accNum, double rate) {
        super(accNum); // Calls parent constructor
        this.interestRate = rate;
    }
    void addInterest() { System.out.println("Interest added: " + interestRate); }
}

Trace: Constructor Execution

Step Action
1 SavingsAccount obj = new SavingsAccount("SA123", 5.0);
2 Account constructor runs (super("SA123")).
3 SavingsAccount constructor initializes interestRate = 5.0.

4. Method Overriding

  • Child class redefines a parent class method with the same signature.
  • Uses @Override annotation (best practice for clarity).
  • Rules:
    • Must have same return type (or covariant return type in Java 5+).
    • Must not be private, static, or final.
    • Can throw broader exceptions than the parent.

Example: Shape Hierarchy

class Shape {
    void draw() { System.out.println("Drawing a shape"); }
}

class Circle extends Shape {
    @Override
    void draw() { System.out.println("Drawing a circle"); }
}

Visual: Method Overriding Trace

sequenceDiagram
    participant Parent as Shape
    participant Child as Circle
    Parent->>Child: draw() called
    Child->>Child: Overrides Parent.draw()
    Child->>Child: Prints "Drawing a circle"

Real-World Tie-In: Ncell Billing System

  • A Customer class has a calculateBill() method.
  • PrepaidCustomer overrides it to apply discounts, while PostpaidCustomer applies late fees.
  • Polymorphism lets the system call the correct version dynamically.

5. Abstract Classes

  • Cannot be instantiated (use new).
  • Can have abstract methods (no body) and concrete methods (with body).
  • Forces subclasses to implement abstract methods.
  • Uses abstract keyword.

Syntax:

abstract class Vehicle {
    abstract void start(); // No implementation
    void stop() { System.out.println("Vehicle stopped"); } // Concrete method
}

Example: Employee Hierarchy

abstract class Employee {
    private String name;
    abstract double calculateSalary(); // Must be implemented by subclasses
    void display() { System.out.println("Name: " + name); }
}

class Manager extends Employee {
    @Override
    double calculateSalary() { return 50000; }
}

Visual: Abstract Class Structure

classDiagram
    class Employee {
        <<abstract>>
        +calculateSalary()
        +display()
    }
    class Manager {
        +calculateSalary()
    }
    Employee <|-- Manager

Real-World Tie-In: eSewa Payment Processing

  • PaymentGateway is an abstract class with:
    • Abstract method: processPayment() (implemented by KhaltiGateway, EbsewayGateway).
    • Concrete method: logTransaction() (shared logic).
  • Ensures all payment methods follow the same transaction logging protocol.

6. Interfaces

  • Pure abstraction: Only abstract methods (before Java 8) or default/static methods (Java 8+).
  • Supports multiple inheritance (a class can implement multiple interfaces).
  • Uses implements keyword.
  • All methods are public by default.

Syntax:

interface Flyable {
    void fly(); // Public abstract by default
    default void land() { System.out.println("Landing"); } // Java 8+
}

Example: Comparable Interface

class Student implements Comparable<Student> {
    int rollNo;
    @Override
    public int compareTo(Student other) {
        return this.rollNo - other.rollNo; // Sort by roll number
    }
}

Visual: Interface Implementation

classDiagram
    class Flyable {
        <<interface>>
        +fly()
        +land()
    }
    class Bird {
        +fly()
    }
    Flyable <|-- Bird

Real-World Tie-In: Daraz Order Queue

  • Order class implements Comparable<Order> to sort orders by:
    • Priority (e.g., order.compareTo(other) returns -1 if higher priority).
    • Time (FIFO for same-priority orders).
  • Ensures fair and efficient order processing.

7. Key Differences: Abstract Class vs. Interface

Feature Abstract Class Interface
Instantiation Cannot be instantiated. Cannot be instantiated.
Methods Can have abstract + concrete methods. Only abstract methods (until Java 8).
Constructors Can have constructors. No constructors.
Inheritance Single inheritance only. Multiple inheritance allowed.
Fields Can have non-final fields. Only public static final fields.
Access Modifiers Methods can be private, protected. All methods are public by default.

Example: Abstract Class vs. Interface

// Abstract Class
abstract class Animal {
    abstract void sound();
    void eat() { System.out.println("Eating..."); }
}

// Interface
interface Swimmable {
    void swim();
    default void dive() { System.out.println("Diving..."); }
}

8. Special Keywords in Inheritance

Keyword Purpose
super Calls parent class constructor/method.
@Override Indicates method overriding (compiler checks for errors).
final Prevents method/class from being overridden/inherited.
static Hides parent class method (not overrides).

Example: super and final

class Parent {
    final void display() { System.out.println("Parent display"); }
}

class Child extends Parent {
    // ERROR: Cannot override final method
    // void display() { ... }
}

9. Inheritance in Action: Worked Example

Problem: Model a Nepalese University system where:

  • University has name and establishedYear.
  • Campus inherits from University and adds location.
  • Student inherits from Campus and adds rollNumber.

Solution:

class University {
    String name;
    int establishedYear;
    University(String name, int year) {
        this.name = name;
        this.establishedYear = year;
    }
    void displayInfo() {
        System.out.println(name + " (Est. " + establishedYear + ")");
    }
}

class Campus extends University {
    String location;
    Campus(String name, int year, String loc) {
        super(name, year); // Calls University constructor
        this.location = loc;
    }
    void displayCampus() {
        displayInfo(); // Inherited method
        System.out.println("Location: " + location);
    }
}

class Student extends Campus {
    String rollNumber;
    Student(String name, int year, String loc, String roll) {
        super(name, year, loc);
        this.rollNumber = roll;
    }
    void displayStudent() {
        displayCampus();
        System.out.println("Roll No: " + rollNumber);
    }
}

Trace: Object Creation

Output:

TU (Est. 1959)
Location: Kirtipur
Roll No: S123

In the Real World

  1. Khalti Payment Gateway

    • Uses interfaces like PaymentProcessor to support multiple payment methods (credit card, mobile wallet).
    • Each method (e.g., KhaltiProcessor, EbsewayProcessor) implements PaymentProcessor with its own process() logic.
    • Polymorphism lets Khalti call the correct processor dynamically based on user choice.
  2. Pathao Driver App

    • Inheritance hierarchy:
      • Vehicle (abstract) → Car, Bike (concrete classes).
      • Driver (abstract) → CarDriver, BikeDriver (override calculateEarnings()).
    • Real-time example: A CarDriver earns more per km than a BikeDriver, so calculateEarnings() is overridden.
  3. NTC Traffic Management System

    • Abstract class: Vehicle with abstract calculateFine().
    • Subclasses:
      • Car (fine = Rs. 500 for speeding).
      • Motorcycle (fine = Rs. 300 for speeding).
    • Polymorphism: The system calls calculateFine() on any Vehicle object, and the correct subclass logic runs.

Exam Tip

What Examiners Love to Test

  1. Code Writing (30-40%)

    • Write a program with inheritance, method overriding, or abstract classes/interfaces.
    • Example Question: "Create a Shape hierarchy with Circle and Rectangle classes that override area()."
    • Do: Use @Override, super(), and proper access modifiers.
    • Avoid: Forgetting to call super() in constructors or missing abstract method implementations.
  2. Conceptual Questions (30-40%)

    • Differentiate abstract class vs. interface.
    • Explain types of inheritance with examples.
    • Describe the use of extends and implements.
    • Example Question: "Why can’t Java support multiple inheritance of classes?" Answer: To avoid the "Diamond Problem" (ambiguous method calls from two parents).
  3. Scenario-Based (20-30%)

    • Apply inheritance to real-world systems (e.g., banking, e-commerce).
    • Example Question: "How would you model a university system using inheritance?" Answer: Use Person (abstract) → Student, Teacher (override calculateFee()/calculateSalary()).
  4. Error Spotting (10%)

    • Identify compilation errors in inheritance code (e.g., missing @Override, incorrect access modifiers).
    • Example: Spotting that private methods cannot be overridden.

Common Mistakes to Avoid

  • Forgetting super() in constructors → Compiler error.
  • Using extends with interfaces → Syntax error.
  • Overriding a method with a less accessible modifier (e.g., public to private) → Compile-time error.
  • Not marking abstract methods in subclasses → Compile-time error.

Quick Revision Checklist

Before the exam, verify you can: ✅ Explain the four types of inheritance in Java. ✅ Write a program with method overriding and @Override. ✅ Differentiate abstract classes and interfaces. ✅ Use super() and this() correctly. ✅ Model a real-world hierarchy (e.g., animals, university, banking).


Pro Tip: For GUI-based questions (like checking even/odd numbers), combine inheritance with AWT/Swing (e.g., extend JFrame for the main window). Always include event handling (e.g., ActionListener) for buttons.

Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 5.

Discussion

Loading…