Unit 4: Object-Oriented Programming
Welcome to the most important concept in Java: Object-Oriented Programming (OOP). We use classes as blueprints to define our robot's mechanisms, and we create objects from those blueprints to control the actual hardware.
A class is a template for creating objects. It bundles together data (fields) and behaviors (methods). Think of the CAD design for a robot intake—that's the class. It defines the properties (like motor type) and actions (like spinning the rollers).
// This class is a blueprint for any intake mechanism
public class Intake {
// 1. Fields (Data)
// These are the attributes that define the state of an intake.
private Spark intakeMotor;
private DigitalInput noteSensor;
private boolean isIntaking;
// 2. Constructor (How to build the object)
// This runs once when a new Intake object is created.
public Intake(int motorPort, int sensorPort) {
intakeMotor = new Spark(motorPort);
noteSensor = new DigitalInput(sensorPort);
isIntaking = false;
}
// 3. Methods (Behaviors)
// These are the actions the intake can perform.
public void start() {
intakeMotor.set(0.8);
isIntaking = true;
}
public void stop() {
intakeMotor.set(0.0);
isIntaking = false;
}
public boolean hasNote() {
// The sensor is inverted, so false means a note is present.
return !noteSensor.get();
}
}
An object is a specific instance of a class. If the `Intake` class is the blueprint, the actual, physical intake on the robot is the object. You create an object from a class using the `new` keyword.
// In your main robot code (e.g., RobotContainer.java)
// Create an actual Intake object from the Intake class blueprint.
// We are telling it our intake motor is on port 5 and our sensor is on port 1.
Intake robotIntake = new Intake(5, 1);
// Now we can use the object to control the real hardware
robotIntake.start();
if (robotIntake.hasNote()) {
robotIntake.stop();
}
Notice the `private` keyword on the fields in the `Intake` class. This is encapsulation. It means the internal data of an object (like its motor) is hidden from the outside world and can only be accessed through its public methods (`start()`, `stop()`). This prevents other parts of the code from directly and dangerously interfering with the mechanism.
A constructor is a special method that is called exactly once when an object is created with the `new` keyword. Its main job is to set up the initial state of the object. A constructor always has the same name as the class and has no return type.
public class Intake {
private Spark intakeMotor;
// This is the constructor. It requires a motorPort to be provided.
public Intake(int motorPort) {
// It initializes the intakeMotor field.
this.intakeMotor = new Spark(motorPort);
}
}
The `this` keyword is used to distinguish between a field (like `this.intakeMotor`) and a parameter with the same name.
Question: What is the primary purpose of a class's constructor?