Web Analytics

Methods in Classes

Intermediate ~15 min read

Methods define the behavior of objects. While fields store data (state), methods perform actions (behavior).

Defining Methods

A method definition looks like this:

public class Car {
    // Field
    int speed = 0;

    // Method
    public void accelerate() {
        speed += 10;
        System.out.println("Speed is now " + speed);
    }
}

Calling Methods

To use a method, you must first create an instance (object) of the class, then use the dot . operator.

Car myCar = new Car();
myCar.accelerate(); // Calls the method

Full Example

Output
Click Run to execute your code