What this topic covers
8 subtopics- static members14
- final and const11
- Static initialisation6
- this5
- classmethod and staticmethod4
- super3
- Class vs instance attributes1
- Class-level hooks1
- Beginner 15
- Intermediate 15
- Advanced 15
About this topic
Four small keywords cause a large share of OOPs output puzzles. static members belong to the class (one copy shared by all objects); instance members belong to each object. final (Java) and const (C++) stop reassignment – of a variable, an override or a subclass – but not mutation of the object a final reference points to. this is the current object; super reaches the parent's version of a member. Python spells these ideas as class attributes, @classmethod, @staticmethod, self and super().
Free preview
Sample questions
Try each one first, then open the answer for the explanation and why the other options are wrong.
What does this print?
public class Main {
static class Visitor {
static int total = 0;
final int id;
Visitor() { total++; id = total; }
}
public static void main(String[] args) {
Visitor a = new Visitor();
Visitor b = new Visitor();
Visitor c = new Visitor();
System.out.println(Visitor.total + " " + b.id + " " + a.id);
}
}
Show answer and explanation
Explanation
total is static, so all Visitors share one counter; id is an instance field, so each object keeps the value it had when it was created.
Why the other options are wrong
- Aid is copied at construction time.
- BEach visitor gets the next number.
- CThe static counter is shared, not per object.
Static fields are initialised in the order they appear. What does this print?
public class Main {
static int a = Main.b + 1;
static int b = 5;
static int c = b + 1;
public static void main(String[] args) {
System.out.println(a + " " + b + " " + c);
}
}
Show answer and explanation
Explanation
When a is initialised, b still holds its default 0, so a = 1. (Writing just b there is an "illegal forward reference" compile error; qualifying it as Main.b sidesteps the check and exposes the default value.)
Why the other options are wrong
- AThe qualified name compiles.
- Bb is still 0 when a is computed.
- Ca adds 1.
What goes wrong when this runs?
public class Main {
static class Rates {
static final int DIVISOR = load();
static final int RATE = 100 / DIVISOR;
static int load() { return 0; }
}
public static void main(String[] args) {
System.out.println(Rates.RATE);
}
}
Show answer and explanation
Explanation
An exception thrown while initialising a class is wrapped in ExceptionInInitializerError; later uses of the class throw NoClassDefFoundError. Keep static initialisers simple.
Why the other options are wrong
- AInteger division by zero throws.
- COnly floating-point division gives Infinity.
- DIt compiles.