Home / Summer / Week 6
Summer · Week 6 of 8

Inheritance & Polymorphism

Building class hierarchies, reusing code, and the OOP features behind WPILib itself.

Why this matters: When you extend SubsystemBase or Command in WPILib, you're using inheritance. These are abstract classes. Understanding this week means understanding how the entire command-based framework works under the hood.

Inheritance

A child class can extend a parent class and inherit all its methods and fields. The child can add new methods and override existing ones.

java
public class Animal {
    public void speak() { System.out.println("..."); }
}

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

// FRC equivalent:
public class DriveSubsystem extends SubsystemBase {
    @Override
    public void periodic() { /* runs every 20ms */ }
}
extends
Inherit from a class
Child gets all public/protected methods and fields. Can only extend one class.
super()
Call parent constructor
Must be the first line in child constructor. Initializes the parent's fields before child adds its own.
@Override
Replace a parent method
Write a new version of the method in the child class. Parent version is replaced for that object.
abstract
Must be implemented
Abstract methods have no body — child classes must provide the implementation. Can't instantiate abstract classes.

Abstract Classes

SubsystemBase and Command in WPILib are abstract. They define the structure every subsystem/command must follow, but leave the specifics to you.

java — simplified WPILib pattern
public abstract class Command {
    public void    initialize() {}   // optional to override
    public void    execute()    {}
    public void    end(boolean interrupted) {}
    public boolean isFinished() { return false; }
}

// Your command extends it and overrides what it needs
public class DriveCommand extends Command {
    @Override
    public void execute() { drive(joystick.getY()); }
}

Interfaces

An interface is a contract — a list of methods a class promises to implement. Unlike inheritance, a class can implement multiple interfaces.

java
public interface Loggable {
    String getLogData(); // no body — must implement
}

public class Drivetrain extends SubsystemBase implements Loggable {
    @Override
    public String getLogData() {
        return "Left: " + leftSpeed + " Right: " + rightSpeed;
    }
}

Fill in the Blanks

// DriveSubsystem inherits from SubsystemBase
public class DriveSubsystem SubsystemBase { }
// Override the speak method from Animal

public void speak() { System.out.println("Woof"); }
// Implement an interface
public class Shooter Loggable { }

Knowledge Check