Java 26-Day Course - Day 9: Classes and Objects

Day 9: Classes and Objects

In Object-Oriented Programming (OOP), a class is a blueprint and an object is an actual entity created from that blueprint. It’s like having a car blueprint (class) from which you can build multiple cars (objects). Java is a purely object-oriented language where all code resides within classes.

Defining Classes and Creating Objects

We design classes with fields (attributes) and methods (behaviors).

public class Student {
    // Fields (attributes)
    String name;
    int age;
    String major;
    double gpa;

    // Methods (behaviors)
    void introduce() {
        System.out.println("Hello, my name is " + name + ".");
        System.out.println("Major: " + major + ", GPA: " + gpa);
    }

    void study(String subject) {
        System.out.println(name + " is studying " + subject + ".");
    }

    boolean isPassing() {
        return gpa >= 2.0;
    }

    public static void main(String[] args) {
        // Creating objects
        Student student1 = new Student();
        student1.name = "Alice";
        student1.age = 22;
        student1.major = "Computer Science";
        student1.gpa = 3.8;

        Student student2 = new Student();
        student2.name = "Bob";
        student2.age = 21;
        student2.major = "Business Administration";
        student2.gpa = 4.2;

        student1.introduce();
        student2.introduce();
        student1.study("Java");
        System.out.println("Passing: " + student1.isPassing());
    }
}

Constructors

Constructors are special methods that are automatically called when an object is created. They share the same name as the class and have no return type.

public class BankAccount {
    String owner;
    String accountNumber;
    long balance;

    // Default constructor
    BankAccount() {
        this.owner = "Unassigned";
        this.accountNumber = "000-000-000";
        this.balance = 0;
    }

    // Constructor with parameters
    BankAccount(String owner, String accountNumber) {
        this.owner = owner;
        this.accountNumber = accountNumber;
        this.balance = 0;
    }

    // Constructor that initializes all fields
    BankAccount(String owner, String accountNumber, long balance) {
        this.owner = owner;
        this.accountNumber = accountNumber;
        this.balance = balance;
    }

    void deposit(long amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println(amount + " deposited. Balance: " + balance);
        }
    }

    void withdraw(long amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            System.out.println(amount + " withdrawn. Balance: " + balance);
        } else {
            System.out.println("Insufficient balance! Current balance: " + balance);
        }
    }

    void showInfo() {
        System.out.println("[" + accountNumber + "] " + owner + " - Balance: " + balance);
    }

    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount();
        BankAccount acc2 = new BankAccount("Alice", "110-234-5678");
        BankAccount acc3 = new BankAccount("Bob", "110-987-6543", 1000000);

        acc2.deposit(500000);
        acc2.withdraw(200000);
        acc2.showInfo();

        acc3.showInfo();
    }
}

The this Keyword and Method Chaining

this refers to the current object itself. It is used to distinguish between fields and parameters with the same name, or in method chaining patterns.

public class Pizza {
    String size;
    String dough;
    boolean cheese;
    boolean pepperoni;
    boolean mushroom;

    Pizza(String size) {
        this.size = size;
        this.dough = "regular";
        this.cheese = false;
        this.pepperoni = false;
        this.mushroom = false;
    }

    // Method chaining: return this to enable consecutive calls
    Pizza setDough(String dough) {
        this.dough = dough;
        return this;
    }

    Pizza addCheese() {
        this.cheese = true;
        return this;
    }

    Pizza addPepperoni() {
        this.pepperoni = true;
        return this;
    }

    Pizza addMushroom() {
        this.mushroom = true;
        return this;
    }

    void describe() {
        System.out.println("=== Pizza Order ===");
        System.out.println("Size: " + size);
        System.out.println("Dough: " + dough);
        System.out.println("Cheese: " + (cheese ? "added" : "none"));
        System.out.println("Pepperoni: " + (pepperoni ? "added" : "none"));
        System.out.println("Mushroom: " + (mushroom ? "added" : "none"));
    }

    public static void main(String[] args) {
        // Clean configuration with method chaining
        Pizza myPizza = new Pizza("Large")
            .setDough("Thin")
            .addCheese()
            .addPepperoni()
            .addMushroom();

        myPizza.describe();
    }
}

Static Members

Fields and methods shared at the class level. They can be used without creating an object.

public class Counter {
    // Static field: shared by all objects
    static int totalCount = 0;

    // Instance field: separate for each object
    String name;
    int id;

    Counter(String name) {
        this.name = name;
        totalCount++;
        this.id = totalCount;
    }

    // Static method: called using the class name
    static int getTotalCount() {
        return totalCount;
    }

    // Instance method
    void showInfo() {
        System.out.println("ID: " + id + ", Name: " + name);
    }

    public static void main(String[] args) {
        System.out.println("Total count: " + Counter.getTotalCount()); // 0

        Counter c1 = new Counter("First");
        Counter c2 = new Counter("Second");
        Counter c3 = new Counter("Third");

        c1.showInfo(); // ID: 1
        c2.showInfo(); // ID: 2
        c3.showInfo(); // ID: 3

        System.out.println("Total count: " + Counter.getTotalCount()); // 3
    }
}

Today’s Exercises

  1. Book Management: Create a Book class with fields: title, author, price, ISBN. Implement constructor overloading (2 or more), a showInfo() method, and an applyDiscount(int percent) method.

  2. Coordinate Calculator: Create a Point class with fields: x, y (double). Implement a distanceTo(Point other) method that calculates the distance between two points, and a midPoint(Point other) method that returns the midpoint.

  3. Auto-Generated Employee ID: Implement an Employee class that uses a static variable to automatically assign IDs in the format “EMP-001”, “EMP-002” each time an object is created.

Was this article helpful?