Classes & Objects
Dashboard
Topic 8/30
Home › Classes & Objects

🏗️ Classes & Objects

Dive into Object-Oriented Programming (OOP) in Java by understanding classes, objects, and methods.

What are Classes and Objects?

A class is a blueprint or template for creating objects. An object is an instance of a class that holds state (fields) and behavior (methods).

BankAccount.java Java
public class BankAccount {
    // Fields (State)
    String accountHolder;
    double balance;
    
    // Methods (Behavior)
    public void deposit(double amount) {
        balance += amount;
        System.out.println(amount + " deposited.");
    }
    
    public void withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
            System.out.println(amount + " withdrawn.");
        } else {
            System.out.println("Insufficient balance!");
        }
    }
    
    public static void main(String[] args) {
        // Object Creation
        BankAccount acc = new BankAccount();
        acc.accountHolder = "Alice";
        acc.deposit(1000);
        acc.withdraw(400);
        System.out.println("Current Balance: " + acc.balance);
    }
}

Static Fields & Methods

The static keyword means that the variable or method belongs to the class itself, rather than to any specific instance (object).

StaticDemo.java Java
public class StaticDemo {
    // Static variable shared across all instances
    static int instanceCount = 0;
    
    public StaticDemo() {
        instanceCount++;
    }
    
    // Static method
    public static void displayCount() {
        System.out.println("Total instances: " + instanceCount);
    }
    
    public static void main(String[] args) {
        new StaticDemo();
        new StaticDemo();
        new StaticDemo();
        
        StaticDemo.displayCount(); // Calls the static method
    }
}

Method Overloading

Method overloading allows a class to have multiple methods with the same name, provided their parameter lists are different (number, type, or order of parameters).

Calculator.java Java
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    
    public double add(double a, double b) {
        return a + b;
    }
    
    public int add(int a, int b, int c) {
        return a + b + c;
    }
    
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 10));       // Calls int version
        System.out.println(calc.add(5.5, 2.2));    // Calls double version
        System.out.println(calc.add(1, 2, 3));     // Calls 3-parameter version
    }
}