Learning Objectives

Understand Inheritance

Learn how to create class hierarchies and promote code reuse

Method Overriding

Master method overriding and the @Override annotation

Abstract Classes

Learn abstract classes and interfaces for defining contracts

Polymorphism

Understand polymorphism and dynamic method dispatch

Introduction to Inheritance

What is Inheritance?

Inheritance is a mechanism that allows a class to inherit properties and methods from another class. It promotes code reuse and establishes a relationship between classes.

Inheritance vs C

C

No built-in inheritance; you'd use composition or function pointers

Java

Built-in inheritance with extends keyword

Types of Inheritance

Single Inheritance

Java supports single inheritance for classes (a class can extend only one class).

public class Vehicle {
    protected String brand;
    protected String model;
    
    public void start() {
        System.out.println("Vehicle starting...");
    }
}

public class Car extends Vehicle {
    private int numDoors;
    
    public Car(String brand, String model, int numDoors) {
        this.brand = brand;
        this.model = model;
        this.numDoors = numDoors;
    }
}

Multilevel Inheritance

A class can inherit from a derived class, making it the base class for a new derived class.

public class Animal {
    protected String name;
}

public class Mammal extends Animal {
    protected boolean hasFur;
}

public class Dog extends Mammal {
    private String breed;
    
    public Dog(String name, boolean hasFur, String breed) {
        this.name = name;      // From Animal
        this.hasFur = hasFur;  // From Mammal
        this.breed = breed;    // Dog's own
    }
}

Method Overriding

What is Method Overriding?

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its parent class.

The @Override Annotation

The @Override annotation helps catch errors at compile time and makes code more readable.

public class Animal {
    public void makeSound() {
        System.out.println("Some animal sound");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof! Woof!");
    }
}

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}

The super Keyword

The super keyword refers to the parent class and is used to call parent class methods and constructors.

public class Person {
    protected String name;
    protected int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Student extends Person {
    private String studentId;
    
    public Student(String name, int age, String studentId) {
        super(name, age);  // Call parent constructor
        this.studentId = studentId;
    }
}

Abstract Classes

What are Abstract Classes?

Abstract classes are classes that cannot be instantiated and may contain abstract methods (methods without implementation).

Abstract Methods

Abstract methods are declared without implementation and must be implemented by concrete subclasses.

public abstract class Shape {
    protected String color;
    
    public abstract double getArea();  // Abstract method
    public abstract double getPerimeter();  // Abstract method
    
    public String getColor() {  // Concrete method
        return color;
    }
}

public class Circle extends Shape {
    private double radius;
    
    public Circle(String color, double radius) {
        this.color = color;
        this.radius = radius;
    }
    
    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
    
    @Override
    public double getPerimeter() {
        return 2 * Math.PI * radius;
    }
}

Interfaces

What are Interfaces?

Interfaces are abstract types that define a contract for classes to implement. They contain only abstract methods (before Java 8) and constants.

Interface Definition

public interface Drawable {
    void draw();  // Abstract method (public abstract by default)
    String getColor();  // Abstract method
}

public interface Movable {
    void move(int x, int y);
    boolean canMove();
}

Implementing Interfaces

A class can implement multiple interfaces.

public class Circle implements Drawable, Movable {
    private String color;
    private int x, y;
    
    @Override
    public void draw() {
        System.out.println("Drawing circle at (" + x + ", " + y + ")");
    }
    
    @Override
    public String getColor() {
        return color;
    }
    
    @Override
    public void move(int newX, int newY) {
        x = newX;
        y = newY;
    }
    
    @Override
    public boolean canMove() {
        return true;
    }
}

Practical Examples

Employee Management System

public abstract class Employee {
    protected String name;
    protected String id;
    protected double baseSalary;
    
    public Employee(String name, String id, double baseSalary) {
        this.name = name;
        this.id = id;
        this.baseSalary = baseSalary;
    }
    
    public abstract double calculateSalary();
    
    public String getName() { return name; }
    public String getId() { return id; }
}

public class SalariedEmployee extends Employee {
    private double bonus;
    
    public SalariedEmployee(String name, String id, double baseSalary, double bonus) {
        super(name, id, baseSalary);
        this.bonus = bonus;
    }
    
    @Override
    public double calculateSalary() {
        return baseSalary + bonus;
    }
}

public class HourlyEmployee extends Employee {
    private int hoursWorked;
    private double hourlyRate;
    
    public HourlyEmployee(String name, String id, double hourlyRate) {
        super(name, id, 0);  // Base salary not applicable
        this.hourlyRate = hourlyRate;
        this.hoursWorked = 0;
    }
    
    public void addHours(int hours) {
        if (hours > 0) {
            hoursWorked += hours;
        }
    }
    
    @Override
    public double calculateSalary() {
        return hoursWorked * hourlyRate;
    }
}

Key Differences from C

Concept C Java
Inheritance No built-in support Built-in with extends
Method Overriding Function pointers Built-in polymorphism
Abstract Classes Not supported abstract keyword
Interfaces Not supported interface keyword
Multiple Inheritance Not supported for classes Supported via interfaces
Polymorphism Manual implementation Built-in runtime polymorphism

Summary

In this module, you've learned:

  • ? How to create class hierarchies using inheritance
  • ? Method overriding and the importance of the @Override annotation
  • ? Abstract classes and interfaces for defining contracts
  • ? Polymorphism and dynamic method dispatch
  • ? The Object class and its important methods
  • ? Final classes, methods, and variables
  • ? Key differences between Java inheritance and C programming

Next Steps

  1. Complete the exercises in the exercises.md file
  2. Practice creating class hierarchies and implementing interfaces
  3. Move to Module 6: Arrays and Collections

?? Module 5 Complete!

You now have a solid understanding of inheritance and polymorphism. Time to learn about arrays and collections!