1.3.1 Object Oriented Programming - Brickwolves/CodeCampWiki GitHub Wiki

The key to most of the code we do at FTC is something called OOP. Object Oriented Programming. People use all sorts of metaphors to explain OOP because it's a pretty weird concept to grasp at first, but you can think about like a car company.

Say we just started a car dealership and we want to keep track of all the cars we sell. We could write them all down, that would look like this.

String car1 = "car1isa2004redchevySUVwith50000milesonit"
String car2 = "car2isa2008bluefordpickuptruckwith20000milesonit"
String car3 = "car3isa2002greyhondasedanwith75000milesonit"
String car4 = "car4isa2016silveraudisportscarwith3000milesonit"
String car5 = "car5isa2021blacknissansedanwith5000milesonititsalsoelectric"

So, that's pretty clearly not the best way. Now this other way, Object Oriented Programming, is going to look a lot more complicated, but in reality it's not and we'll explain why.

public class Car {
    // Attributes
    private String make;
    private String model;
    private int year;
    private String color;
    private double mileage;
    
    // Constructor
    public Car(String make, String model, int year, String color, double mileage) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.color = color;
        this.mileage = mileage;
    }
    
    // Methods to access attributes (getters and setters)
    public String getMake() {
        return make;
    }
    
    public void setMake(String make) {
        this.make = make;
    }
    
    public String getModel() {
        return model;
    }
    
    public void setModel(String model) {
        this.model = model;
    }
    
    public int getYear() {
        return year;
    }
    
    public void setYear(int year) {
        this.year = year;
    }
    
    public String getColor() {
        return color;
    }
    
    public void setColor(String color) {
        this.color = color;
    }
    
    public double getMileage() {
        return mileage;
    }
    
    public void setMileage(double mileage) {
        this.mileage = mileage;
    }
    
    // Method to display car information
    public void displayCarInfo() {
        System.out.println("Make: " + make);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
        System.out.println("Color: " + color);
        System.out.println("Mileage: " + mileage);
    }
 
}

So the reason this is better is because if I want to access information about the car, once I have this class, instead of writing this:

System.out.println("car5isa2021blacknissansedanwith5000milesonititsalsoelectric")

and then sorting through what all of that means, I can do this:

Car myCar = new Car("Toyota", "Camry", 2020, "Blue", 15000);

myCar.displayCarInfo();