Classes & Objects
You've learned about variables, methods, and control flow. Now it's time to put them all together. Classes are blueprints that let you create your own custom "data types", and objects are instances of those classes.
What is a Class?
A class is like a blueprint or template. It defines what data (variables) and actions (methods) something should have, but it doesn't create the actual thing yet.
public class Robot {
// Variables (what the robot has)
private DcMotor leftMotor;
private DcMotor rightMotor;
private boolean isMoving;
// Methods (what the robot can do)
public void moveForward() {
leftMotor.setPower(0.5);
rightMotor.setPower(0.5);
isMoving = true;
}
public void stop() {
leftMotor.setPower(0);
rightMotor.setPower(0);
isMoving = false;
}
}
What is an Object?
An object is an instance of a class.
// Create objects from the Robot class
Robot myRobot = new Robot(); // This creates one robot
Constructors
A constructor is a special method that runs when you create a new object. It sets up the initial state:
public class Hardware {
private DcMotorEx motor1;
// Constructor - runs when you create a new Hardware
public GameTimer(hardwareMap hw) {
motor1 = hw.get(DcMotorEx.class,"m1");
}
}
// Using the constructor
Hardware hardwareClass = new Hardware(hardwareMap);
Quick Reference
| Concept | What It Is | Example |
|---|---|---|
| Class | Blueprint/template | public class Robot { ... } |
| Object | Instance of a class | Robot myRobot = new Robot(); |
| Constructor | Setup method for new objects | public Robot(String name) { ... } |