Skip to the workspace
Pebellslearn by building
Classes and Objects  ›  Lesson

Attributes and Methods

Attributes and Methods 13 minFields store each object's state and methods act on that state, with the header stating the parameters a method takes and the type of value it returns.

java / Attributes and Methods

Explore each scene at your own pace.

01 · The rule

The rule

Attributes and Methods

Fields store each object's state and methods act on that state, with the header stating the parameters a method takes and the type of value it returns.

Trace a method call as it reads or changes an object's fields.

A drink that only stores data is half an object. Brew Bar's orders need to do things: add a cup, work out their total, print a receipt. Putting that behaviour inside the class, next to the data it uses, is what makes objects worth having.

The rule

Fields are what an object knows; methods are what it does.

Attributes, usually called fields, hold each object's state. Methods are the actions, and they can read and change that state directly:

public class Order {
    String customer;
    int cups;
    int unitCents;

    Order(String customer, int unitCents) {
        this.customer = customer;
        this.unitCents = unitCents;
        this.cups = 1;
    }

    void addCup() {
        cups++;
    }

    int totalCents() {
        return cups * unitCents;
    }

    String receipt() {
        return customer + ": " + cups + " x " + unitCents + " = " + totalCents();
    }
}

Read a method header from left to right:

  • Return type: what the method hands back. int totalCents() promises an int, and every path through it must return one. void means it hands back nothing.
  • Name: a verb or question, in camelCase, such as addCup or isLarge.
  • Parameters: the inputs in brackets, each with a type. addCups(int n) would take one; () means none.

Inside a method, a field name such as cups means this object's cups. Methods can also call each other: receipt() uses totalCents() rather than repeating the multiplication.

Calling a method uses a dot on a particular object:

Order o = new Order("Asha", 300);
o.addCup();
System.out.println(o.receipt());   // Asha: 2 x 300 = 600
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.