AI Hints
Home›Java Tutorial›The this Keyword, Instance Methods and static
Java · Lesson 68 of 120

Instance Methods

What an object can do.

⏱ 2 min read▶ Video at 1:25:22🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Fields are what an object knows. Methods are what an object can do. Methods without static belong to each object, and work with its own fields.

  • Fields: what it knows
  • Methods: what it does
  • Each object's own

Counter.java

A counter has one field, count. Increment adds one to it. Add adds any amount. And get returns the current count. There's no static here. Each method works on the count of whichever object it's called on.

Main.javajava
public class Counter {
    int count;

    void increment() {
        count++;
    }

    void add(int amount) {
        count += amount;
    }

    int get() {
        return count;
    }
}

Calling methods on objects

We make two separate counters. Calling visitors dot increment changes only the visitors counter. Sales gets forty added. Run it. Visitors is three, and sales is forty. Each counter keeps its own count.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Counter visitors = new Counter();
        Counter sales = new Counter();
        visitors.increment();
        visitors.increment();
        visitors.increment();
        sales.add(40);
        System.out.println("Visitors: " + visitors.get());
        System.out.println("Sales: " + sales.get());
    }
}
Output
Visitors: 3
Sales: 40
Also uses Counter.java
public class Counter {
    int count;

    void increment() {
        count++;
    }

    void add(int amount) {
        count += amount;
    }

    int get() {
        return count;
    }
}

Objects bundle data and behaviour

An object keeps its data, and the code that uses that data, together. You ask the object to do things, by calling its methods. The fields are its state. And the methods are its behaviour.

keyvalue
Fieldsstate: count
Methodsbehaviour: increment()
Callobject.method()
Each objectits own state

Summary

Instance methods belong to objects, and work on that object's fields. Call them with a dot. Next, static, which belongs to the class itself.

Key takeaways
  • No static
  • object.method()
  • Works on its own fields
Next up: static — belongs to the class