Java Classes
Classes in OOP
Object-oriented code groups data and behavior into classes. On a robot project, examples include a drivetrain class, a sensor wrapper, or a gamepad helper. Each class describes one kind of thing in the problem you are solving.
Blueprint analogy
A class defines what objects of that type can store and what they can do. A object is one instance built from that class. One ArrayList class; many list objects with different contents.
Example
// Just like ArrayList is a class provided by Java:
ArrayList<Integer> integers = new ArrayList<>();
integers.add(15);
integers.add(34);
integers.add(65);
integers.add(111);
System.out.println(integers.size());
// We can create our own classes for robotics:
FRCRobot competitionBot = new FRCRobot("TeamBot");
competitionBot.initializeHardware();
competitionBot.startAutonomous();One class, many objects
Every object from the same class shares the same fields and methods. Each object has its own values for those fields (team number, battery level, and so on).
Defining a class
Instance variables hold state. Methods define behavior.
public class TeamMember {
// Instance variables (attributes)
private String name;
private int age;
private String role;
// Constructor
public TeamMember(String memberName) {
this.name = memberName;
this.age = 0;
this.role = "Student";
}
// Methods (behaviors)
public void assignRole(String newRole) {
this.role = newRole;
System.out.println(name + " is now the " + newRole);
}
public String getName() {
return this.name;
}
}Encapsulation
Fields declared private are only accessible through methods on the same class (or through accessors you add later). That encapsulation keeps other code from changing internal state in uncontrolled ways.