☕ Java

Classes and Objects in Java

OOP's big idea: model your software the same way you think about the real world. A class is a blueprint, an object is the actual thing. Once this clicks, Java starts to feel natural.

Class = Blueprint, Object = The Real Thing

Think about a car manufacturing plant. The plant has a blueprint that says: every car has a model name, a color, and an engine size. Every car can accelerate, brake, and honk. That blueprint is the class. Each actual car that rolls off the assembly line is an object — an instance of the blueprint. In code: • The class defines what fields (data) and methods (behaviors) all objects of that type will have • Each object has its own copy of the fields, with its own values A class is defined once. You can create as many objects from it as you need.
Java
// Class definition — the blueprint
public class Student {

    // Fields (instance variables) — what every student HAS
    String name;
    int age;
    double gpa;

    // Constructor — how a new student is created
    // Called automatically when you do 'new Student(...)'
    public Student(String name, int age, double gpa) {
        this.name = name;  // 'this' refers to the current object
        this.age = age;
        this.gpa = gpa;
    }

    // Method — what every student can DO
    public void displayInfo() {
        System.out.println("Name: " + name + " | Age: " + age + " | GPA: " + gpa);
    }

    public boolean isHonorsStudent() {
        return gpa >= 3.5;
    }
}

Creating Objects and Using Them

Now let's create actual objects from our Student blueprint:
Java
public class Main {
    public static void main(String[] args) {

        // Create two Student objects from the same blueprint
        Student s1 = new Student("Alice", 20, 3.8);
        Student s2 = new Student("Bob", 22, 3.2);

        // Each object has its own data
        s1.displayInfo();  // Name: Alice | Age: 20 | GPA: 3.8
        s2.displayInfo();  // Name: Bob   | Age: 22 | GPA: 3.2

        // Call methods on objects
        System.out.println(s1.isHonorsStudent());  // true (3.8 >= 3.5)
        System.out.println(s2.isHonorsStudent());  // false

        // Directly access a field
        System.out.println(s1.name);  // Alice
    }
}