Attributes and Methods

Instance Methods

Methods inside a class (without static) are instance methods. They work with the fields of the object they are called on.

Example

public class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.holder = "Suresh";
        acc.deposit(5000);
        acc.withdraw(1200);
        acc.withdraw(10000);
        acc.printBalance();
    }
}

class BankAccount {
    String holder;
    double balance;

    void deposit(double amount) {
        balance += amount;
        System.out.println("Deposited " + amount);
    }

    void withdraw(double amount) {
        if (amount > balance) {
            System.out.println("Insufficient balance for " + amount);
            return;
        }
        balance -= amount;
        System.out.println("Withdrew " + amount);
    }

    void printBalance() {
        System.out.println(holder + " has Rs. " + balance);
    }
}

Output

Deposited 5000.0
Withdrew 1200.0
Insufficient balance for 10000.0
Suresh has Rs. 3800.0

Methods that Return Values

Example

public class Main {
    public static void main(String[] args) {
        Rectangle r = new Rectangle();
        r.width = 4;
        r.height = 2.5;
        System.out.println("Area: " + r.area());
        System.out.println("Perimeter: " + r.perimeter());
        System.out.println("Square? " + r.isSquare());
    }
}

class Rectangle {
    double width;
    double height;

    double area() { return width * height; }
    double perimeter() { return 2 * (width + height); }
    boolean isSquare() { return width == height; }
}

Output

Area: 10.0
Perimeter: 13.0
Square? false

Exercise: Create a class Circle with a field radius and a method area(). Create a circle of radius 3 and print its area.

Show answer
class Circle {
    double radius;
    double area() { return Math.PI * radius * radius; }
}

// in main:
Circle c = new Circle();
c.radius = 3;
System.out.println(c.area());   // 28.274333882308138