Home › Learn › Java › Objects

Classes and objects

Lesson 26 of 40. Bundle data with the methods that work on it.

A class describes a kind of object: the fields it stores and the methods it can run. class Counter { int count; void increment() { count++; } } is a class; Counter c = new Counter(); creates an object (an instance), c.increment(); calls a method on it, and c.count reads its field. Every object has its own fields, so two counters count separately. Methods without static are instance methods: they run on one object and can use its fields directly.

Class names are CapWords. Put extra classes after Main in the file, without public; that is what the lessons so far have done with Policy and the others. Inside Main, static methods and main can create objects of any class in the file.

class Account {
    String owner;
    int balance;

    int deposit(int amount) {
        balance += amount;
        return balance;
    }
}

// in main:
Account a = new Account();
a.owner = "Ada";
a.deposit(50);
System.out.println(a.owner + " " + a.balance);   // Ada 50

Your task

Write class Counter with an int count starting at 0, int increment() that adds one and returns the new count, and void reset() that sets it back to 0. Then write class Rectangle with int width and int height fields and the methods int area() and int perimeter().

Hint 1

class Counter { int count = 0; int increment() { count++; return count; } void reset() { count = 0; } }

Hint 2

int area() { return width * height; } int perimeter() { return 2 * (width + height); }

Show the solution
public class Main {
    public static void main(String[] args) {
        Counter c = new Counter();
        c.increment();
        System.out.println(c.count);
    }
}

class Counter {
    int count = 0;

    int increment() {
        count++;
        return count;
    }

    void reset() {
        count = 0;
    }
}

class Rectangle {
    int width;
    int height;

    int area() {
        return width * height;
    }

    int perimeter() {
        return 2 * (width + height);
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.