← Java from Scratch Lesson 30 of 88 · 10 XP

Classes and objects

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

class Car {
    String model;     // fields
    int year;

    void honk() {     // an instance method — no static
        System.out.println(model + " " + year + ": Beep!");
    }
}

public class Main {
    public static void main(String[] args) {
        Car a = new Car();
        a.model = "Mustang";
        a.year = 1969;
        a.honk();

        Car b = a;           // a second REFERENCE to the same object
        b.year = 2024;
        System.out.println(a.year);   // 2024
    }
}

A file can have only one public class (named after the file); the others go without public.

Task. Finish the class Counter: a field int value and the methods inc(), add(int n), reset(). The program carries out the commands (inc, add N, reset) and prints value.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.