Unit 4: Object-Oriented Programming
The `static` keyword in Java creates a member that belongs to the class itself, rather than to any individual object. This means `static` fields and methods are shared across all instances of a class.
Understanding this distinction is key to mastering object-oriented programming in Java.
A static variable is perfect for data that should be common to all objects of a class. Think of a team number or a counter for how many objects have been created.
public class FRC_Team {
// Instance variable: each team object has its own name
public String teamName;
// Static variable: this is shared across ALL FRC_Team objects
public static int teamCount = 0;
public FRC_Team(String name) {
this.teamName = name;
teamCount++; // Increment the shared counter
}
}
// In your main code:
System.out.println("Teams created so far: " + FRC_Team.teamCount); // Prints 0
FRC_Team team2910 = new FRC_Team("Jack in the Bot");
System.out.println("Teams created so far: " + FRC_Team.teamCount); // Prints 1
FRC_Team team254 = new FRC_Team("The Cheesy Poofs");
System.out.println("Teams created so far: " + FRC_Team.teamCount); // Prints 2
Notice how we access `teamCount` using the class name (`FRC_Team.teamCount`), not an object name. This emphasizes that it belongs to the class.
A static method also belongs to the class and can be called without creating an object. These are often used for utility functions that don't rely on the state of a specific object.
Because a static method isn't tied to any specific object, it cannot access instance variables or instance methods directly. It can only use other static members.
public class RobotMath {
// Instance variable
public double lastResult;
// Static constant (static + final)
public static final double GRAVITY_METERS_PER_SEC_SQ = 9.81;
// Static method: a utility function
public static double inchesToMeters(double inches) {
return inches * 0.0254;
}
// Instance method: uses an instance variable
public double calculate(double input) {
this.lastResult = input * 2;
return this.lastResult;
}
}
// In your main code:
double meters = RobotMath.inchesToMeters(12.0); // Call static method on the class
// double res = RobotMath.calculate(5); // ERROR! Cannot call instance method on a class
The `main` method is always `public static void main(...)` because the Java runtime needs to be able to call it to start your program without first creating an object of your main class.
Question: You have a `Robot` class with a static variable `robotCount` and an instance variable `robotName`. If you create three `Robot` objects, how many copies of `robotCount` and `robotName` exist in memory?