Inheritance

One of the most powerful parts of object oriented programming is inheritance. This is when you create a class based off of another class while adding new features or behavior. In FRC, you will see this the most often in each subsystem where you write extends SubsystemBase. What exactly does this do?

When you write extends SubsystemBase, the class you are creating has all of the variables and methods that the SubsystemBase class has. For example:

class Pivot extends SubsystemBase {
	public Command idleCommand() {
		return Commands.none();
	}
}

Pivot pivot = new Pivot();
pivot.setDefaultCommand(pivot.idleCommand());

Even though the setDefaultCommand method was not defined in the Pivot class, we can still use it because it is a part of the SubsystemBase class.

A class that inherits from another is called a subclass and the class it inherits from is a superclass. The subclass has access to all of the methods and variables in the superclass marked public or protected. The protected access modifier acts just like private but give access to subclasses.

Polymorphism

Sometimes the methods in the superclass need to be modified to fit the new design of the subclass. In this case, you can override a method from the superclass and create it anew. In FRC, this usually looks like overriding the periodic function.

@Override
public void periodic() {
	System.out.println("Hello"); <- Prints every command scheduler loop
}

The SubsytemBase contains an empty periodic function that is run once every command scheduler loop. By overriding it, your version takes the place of the old one. If you want to use the superclass method and override it, you can always access the superclass and its methods using the super keyword.

public class SuperClass {
	public void speak() {
		System.out.println("Hello");
	}
}

public class SubClass extends SuperClass {
	@Override
	public void speak() {
		System.out.println("Subclass Hello")
		super.speak(); <- Runs the original version, saying "Hello"
	}
}

Interfaces

An interface is a special type of class where you declare what methods and variables are in the class but do not define them. An interface is basically a dedicated superclass where you have to implement all of the methods in a subclass.

public interface PivotIO {
	public void setPosition(Angle position);
}

Notice that I declared the method setPosition but did not define what code it contains.