Static versus instance

What belongs to the class and what belongs to each object: shared class attribute, static method without this, constant, calling through the class name and the static context error, in Java.

  • 23 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Understand

A few cards from the deck

  • Static member: what is it?

    Show the answer

    An attribute or method, declared with static, that belongs to the class itself and not to a particular object.

    It exists even if no object has been created: it is reached through the class name, for instance Math.max(3, 8).

  • Which values does this program print?

    ```java
    class Compte {
    static int nb = 0;
    int numero;
    Compte() {
    nb++;
    numero = nb;
    }
    }

    Compte a = new Compte();
    Compte b = new Compte();
    Compte c = new Compte();
    System.out.println(Compte.nb + " " + a.numero + " " + b.numero + " " + c.numero);
    `

    • 3 1 2 3
    • 3 3 3 3
    • 1 1 1 1
    • 3 0 0 0
    Show the answer

    3 1 2 3

    nb is shared: it is 1, 2 then 3 as objects are created, and each constructor copies the current value into its own object's numero, which belongs to that object. The numbers therefore stay 1, 2 and 3.

  • A … attribute exists as a single copy, shared by … the objects of the class.

    Show the answer

    A static attribute exists as a single copy, shared by all the objects of the class.

    By contrast, an instance attribute is duplicated in every object created.

  • Instance member: what is it?

    Show the answer

    An attribute or method, declared without static, that each object has its own version of and that is used on a specific object.

    The rayon of a circle only makes sense for a given circle: an object is needed to read it.

  • Why can Math.max(3, 8) be written without creating a Math with new?

    • Java automatically creates a hidden Math object when the program starts
    • max is static: it belongs to the class
    • Math is a primitive type of the language, not a class
    • max does not need arguments to run
    Show the answer

    max is static: it belongs to the class

    A method that depends on no object state can be static: max uses only its parameters, like the other utility methods of Math.