Learn/Java/10. Classes and records
Lesson 10 of 15
Sign in

Java, lesson 10

Classes and records

So far your data has been loose variables: a name here, a score there. Real programs group related data into types of their own. In Java you do that with classes, and for plain data, with records.

A class bundles state and behaviour

A class is a blueprint. Each object made from it has its own copy of the class's fields (its state) and shares its methods (its behaviour).

Using it:

Some details worth knowing:

  • new creates an object and calls the constructor, which has the class name and no return type. Its job is to put the object in a valid starting state.
  • this.label means "the field of this object", which separates it from the parameter label.
  • private hides a field from code outside the class. Other code must go through methods such as . That is : the class can enforce its own rules (a count never goes negative, a health bar never exceeds 100) because nobody can change the fields behind its back.

2 exercises to try what you just read.

Exercise 1

Game character

Press Ctrl Enter or Check to test your code.

Exercise 2

Delivery route

Press Ctrl Enter or Check to test your code.

getCount()
encapsulation
  • Methods without static are instance methods: you call them on an object, and they see that object's fields.
  • toString decides how the object prints. @Override asks the compiler to check that you are really replacing an inherited method.
  • On this site everything lives in Main.java. You can add more classes in that file as long as only Main is public.

    Records: data without the boilerplate

    Many types are just a few values bundled together: a point, a date range, a product line. Writing fields, a constructor, getters, equals, hashCode and toString by hand for each is tedious. A record gives you all of them from one line:

    Records are immutable: the fields are final, so a point never changes after it is created. To "move" it, you create a new one. You can still add methods, static factory methods, and a compact constructor that validates the values:

    Class or record?

    Use a record when the type is a value defined by its data and does not change: coordinates, money amounts, results. Use a class when the object has a life of its own and its state changes over time through methods: a bank account, a game character, a shopping cart.

    Further reading

    • Creating classes (dev.java)
    • Defining constructors (dev.java)
    • Using record to model immutable data (dev.java)

    Complete the Hero class. A hero has a name and health points (HP) that start at 100.

    • takeHit(int damage) lowers HP, but never below 0.
    • heal(int amount) raises HP, but never above 100.
    • isAlive() returns true while HP is above 0.
    • toString() returns <name>: <hp> HP.

    The first input line is the hero's name. Each following line is hit <n> or heal <n>. After every command, print the hero. At the end print Still standing if the hero is alive, otherwise Knocked out. The main method is already written for you.

    Sample input:

    Sample output:

    Define a record Point(double x, double y) with a method double distanceTo(Point other) that returns the straight-line distance (use Math.hypot(dx, dy)).

    The input has one stop per line, as x y. A delivery van visits the stops in order. Print the total length of the route with two decimals, then the stop farthest from the origin (0, 0), printed with the record's own toString. If two stops are equally far, keep the first. There is always at least one stop.

    Sample input:

    Sample output:

    class Counter {
        private final String label;   // fields
        private int count;
    
        Counter(String label) {       // constructor: runs when you write new Counter(...)
            this.label = label;
            this.count = 0;
        }
    
        void increment() {            // instance method: works on this object's fields
            count++;
        }
    
        int getCount() {
            return count;
        }
    
        @Override
        public String toString() {
            return label + "=" + count;
        }
    }
    Counter clicks = new Counter("clicks");
    clicks.increment();
    clicks.increment();
    System.out.println(clicks.getCount());   // 2
    System.out.println(clicks);              // clicks=2  (println calls toString)
    record Point(int x, int y) { }
    
    Point p = new Point(3, 4);
    System.out.println(p.x());                       // 3   (accessor, no "get")
    System.out.println(p);                           // Point[x=3, y=4]
    System.out.println(p.equals(new Point(3, 4)));   // true: compares the values
    record Temperature(double celsius) {
        Temperature {
            if (celsius < -273.15) {
                throw new IllegalArgumentException("Below absolute zero");
            }
        }
    
        double fahrenheit() {
            return celsius * 9 / 5 + 32;
        }
    }
    Ada
    hit 30
    heal 50
    hit 120
    Ada: 70 HP
    Ada: 100 HP
    Ada: 0 HP
    Knocked out
    0 0
    3 4
    3 0
    Route: 9.00
    Farthest: Point[x=3.0, y=4.0]