Task 3 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.3 Instance methods — calling a method on an object

Lesson

Ask an object to compute something

An instance method can combine the object's fields and return a result. You run it by calling it on the object: object.method(). The dot means "call this method on this particular object," so it works with that object's own field values.


Worked example

class Rectangle {
    int width;
    int height;

    int area() {
        return width * height;   // uses both fields
    }
}

Rectangle r = new Rectangle();
r.width = 4;
r.height = 3;
System.out.println(r.area());   // 12

▶ Try it: area() returns width * height for the object you call it on. Run this, then change the width and height and re-run.



r.area() returns width * height. For width = 4 and height = 3, what does r.area() return?


What does the dot in r.area() mean?


Fill the blank to print the area of rectangle r.


True or false?


Type exactly what this program prints.

class Square {
    int side;
    int area() {
        return side * side;
    }
}

public class Main {
    public static void main(String[] args) {
        Square s = new Square();
        s.side = 5;
        System.out.println(s.area());
    }
}