Java Classes & Objects

A class is a blueprint; an object is an instance of it.

Java
public class Book {
    // fields (state)
    private String title;
    private double price;

    // constructor
    public Book(String title, double price) {
        this.title = title;
        this.price = price;
    }

    // methods (behaviour)
    public double priceWithVat() {
        return price * 1.13;
    }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
}
Java
Book b = new Book("Palpasa Cafe", 480);
System.out.println(b.getTitle());        // Palpasa Cafe
System.out.println(b.priceWithVat());    // 542.4

this refers to the current object — needed above because the parameter and the field share a name.

Encapsulation

Fields are private; access goes through methods. This lets the class enforce its own rules:

Java
public class Account {
    private double balance = 0;

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Must be positive");
        }
        balance += amount;
    }

    public double getBalance() { return balance; }
}

With balance public, any code could set it to −1000. Private plus a validating method makes that impossible.

Constructor overloading

Java
public class Book {
    private String title;
    private double price;

    public Book(String title, double price) {
        this.title = title;
        this.price = price;
    }

    public Book(String title) {
        this(title, 0.0);   // call the other constructor
    }
}

If you write no constructor at all, Java supplies a no-argument default. Write any constructor and that default disappears.

static vs instance

Java
public class Counter {
    private static int total = 0;   // shared by ALL objects
    private int mine = 0;            // one per object

    public void record() {
        total++;
        mine++;
    }

    public static int getTotal() { return total; }
}

A static method cannot use instance fields — there is no object for it to read them from.

toString()

Override it so printing an object is useful:

Java
@Override
public String toString() {
    return "Book{title='" + title + "', price=" + price + "}";
}

Without it, System.out.println(book) prints Book@1b6d3586.

Knowledge Check

4 questions — test your understanding

1

What is the purpose of the `extends` keyword in Java?

2

What does `@Override` annotation do?

3

What is polymorphism in Java?

4

What is the difference between abstract class and interface?