1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 2

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. A final reference 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 (String is 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:

ModifierSame classSame packageSubclass (other package)Anywhere
privateYesNoNoNo
default (none)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

Exam pitfall: a static method cannot use this or super, and a static field is not copied per object.

Try two questions

Question 1 · Tier 4, Analyse

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:

  1. 50 and 50
  2. 5 and 50
  3. 5 and 5
  4. 1 and 50
Show the answer

B. Output '5 50': this.x set the field to 5, the local x shadows it in get2.

Question 2 · Tier 2, Understand

Which modifier allows access from the same package and from subclasses in other packages, but not from unrelated classes elsewhere?

  1. default (package-private)
  2. public
  3. private
  4. protected
Show the answer

D. protected adds subclass access to the package-level access of default.