×

java · level 2 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is a skill every object carries.

So far your methods have been static: they belong to Main, and you hand them everything they need. Leave out static inside your own class, and you get an instance method. Every object carries it, and it can use that object's fields directly.

Call it with the object, a dot and the name: rex.feed(). Inside, hunger means the hunger of rex. Call tiddles.feed(), and the same method works on the hunger of tiddles instead.

main is static, so it has no object of its own. It always names the object before the dot.

public class Main {
    static class Pet {
        String name;
        int hunger;
        Pet(String name, int hunger) {
            this.name = name;
            this.hunger = hunger;
        }
        void feed() { hunger = hunger - 3; }
        boolean isHungry() { return hunger > 5; }
    }
    public static void main(String[] args) {
        Pet rex = new Pet("Rex", 8);
        System.out.println(rex.name + " hungry: " + rex.isHungry());
        rex.feed();
        System.out.println(rex.name + " hungry: " + rex.isHungry());
    }
}

Inside an instance method, hunger and this.hunger mean the same field.