← Java from Scratch Lesson 32 of 88 · 10 XP

Class methods

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

  • an instance method (without static) works with a specific object and sees its fields: circle.area();
  • a static method (static) belongs to the class, and no object is needed: Math.sqrt(2), Integer.parseInt("5"). It doesn't see instance fields — it has no this.
class Circle {
    double r;

    double area() { return Math.PI * r * r; }               // an instance method

    static Circle unit() {                                  // a factory — static
        Circle c = new Circle();
        c.r = 1;
        return c;
    }

    static boolean same(Circle a, Circle b) { return a.r == b.r; }
}

The rule: if a method depends on the object's data, it's an instance method; if it's just a function "on the class's topic", it's static.

Task. Add to Vec an instance method length(), a method add(Vec o) (it returns a new vector) and a static dot(Vec a, Vec b) — the dot product.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.