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.
- Concepts
- Questions
- Sort and link
- 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 33 3 3 31 1 1 13 0 0 0
Show the answer
3 1 2 3nbis shared: it is 1, 2 then 3 as objects are created, and each constructor copies the current value into its own object'snumero, 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
rayonof 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 aMathwithnew?- Java automatically creates a hidden
Mathobject when the program starts maxis static: it belongs to the classMathis a primitive type of the language, not a classmaxdoes not need arguments to run
Show the answer
maxis static: it belongs to the classA method that depends on no object state can be static:
maxuses only its parameters, like the other utility methods ofMath.- Java automatically creates a hidden