Lesson 11 of 25

Classes & Objects

Creating Classes

A class is a blueprint for creating objects. It defines properties (fields) and behaviors (methods).

Example
public class Car {
    // Fields (properties)
    String brand;
    String model;
    int year;
    double speed;

    // Method
    void accelerate(double amount) {
        speed += amount;
        System.out.println(brand + " speed: " + speed + " km/h");
    }

    void brake() {
        speed = Math.max(0, speed - 10);
    }

    String getInfo() {
        return year + " " + brand + " " + model;
    }
}

// Create objects
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.model = "Camry";
myCar.year = 2024;
myCar.accelerate(60);

The this Keyword

The 'this' keyword refers to the current object instance. It's used to distinguish between fields and parameters with the same name.

Example
public class Student {
    private String name;
    private int grade;

    // Using 'this' to refer to the current object
    public void setName(String name) {
        this.name = name;  // this.name = field, name = parameter
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    public String toString() {
        return this.name + " (Grade: " + this.grade + ")";
    }
}