Classes and Objects

Site Admin · 11 Sep 2026 · 12 views

Anatomy of a Class

public class BankAccount {
    // fields: the state of every account
    private String accountHolder;
    private double balance;

    // constructor: runs when an object is created
    public BankAccount(String accountHolder, double balance) {
        this.accountHolder = accountHolder;
        this.balance = balance;
    }

    // methods: the behaviour
    public void deposit(double amount) {
        balance += amount;
    }

    public void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        } else {
            System.out.println("Insufficient funds");
        }
    }

    public double getBalance() {
        return balance;
    }
}

Using the Class

BankAccount acc = new BankAccount("Ravi", 1000);
acc.deposit(250);
acc.withdraw(100);
System.out.println("Balance: " + acc.getBalance()); // 1150

The this Keyword

this refers to the current object. It is needed when a parameter name shadows a field name, as in the constructor above where accountHolder is both a parameter and a field.

Using a Class from Another Class

Main.java
------------
public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("Sara", 500);
        System.out.println(account.getBalance());
    }
}

Note that the two classes may live in the same file only if at most one is public and it matches the file name. Normally each public class gets its own .java file.

Key Points

  • Fields store state, constructors build objects, methods provide behaviour.
  • new ClassName(args) creates an object.
  • this disambiguates fields from same-named parameters.
Share this post:

Comments (0)

Please login or register to comment.