CAP477 · Unit 2: Object-oriented programming
static, final, this and access modifiers
8 practice questions
Key points
- static = per class, shared; static methods use only static members
- final variable once, final method no override, final class no extend
- this separates fields from parameters
- private < default < protected < public
static members belong to the class, not to an instance. A static field is shared by all objects (a.s++ is seen through b.s). A static method can access only static members directly: referencing an instance field from static void f() is the compile error "non-static variable v cannot be referenced from a static context". A static block runs once when the class is loaded, before first use (loaded prints once even if hi() is called twice).
final:
- final variable: assigned once;
final int x = 1; x = 2;fails to compile. Afinalreference cannot be re-pointed but the object can change (final int[] a; a[0] = 9;is legal). - final method: cannot be overridden.
- final class: cannot be extended (
Stringis final). - Constants:
static final int A = 10;
this refers to the current object: this.x = x; separates the field from a parameter of the same name. Without this, a local variable shadows the field (a method with local int x = 50 returns 50 while the field is 5).
Access modifiers:
| Modifier | Same class | Same package | Subclass (other package) | Anywhere |
|---|---|---|---|---|
| private | Yes | No | No | No |
| default (none) | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
Exam pitfall: a static method cannot use this or super, and a static field is not copied per object.
Try two questions
class H { int x=1; H(int x){ this.x = x; } int get2(){ int x = 50; return x; } }. For new H(5), get() returns x and get2() returns:
- 50 and 50
- 5 and 50
- 5 and 5
- 1 and 50
Show the answer
B. Output '5 50': this.x set the field to 5, the local x shadows it in get2.
Which modifier allows access from the same package and from subclasses in other packages, but not from unrelated classes elsewhere?
- default (package-private)
- public
- private
- protected
Show the answer
D. protected adds subclass access to the package-level access of default.