Java interfaces: accessing a constant field declared in an interface via object, class, and interface names — does this compile and run?\n\ninterface Foo141 { \n int k = 0; // implicitly public static final\n}\npublic class Test141 implements Foo141 {\n public static void main(String args[]) {\n int i;\n Test141 test141 = new Test141();\n i = test141.k; // Line 11\n i = Test141.k; // inherited constant\n i = Foo141.k; // interface-qualified\n }\n}

Difficulty: Easy

Correct Answer: Compiles and runs ok.

Explanation:


Introduction / Context:
This program examines how an interface constant (implicitly public static final) can be accessed. In Java, interface fields are constants available through the interface name, through implementing classes, and even (discouraged stylistically) via instances of implementing classes.


Given Data / Assumptions:

  • Foo141.k is implicitly public static final 0.
  • Test141 implements Foo141 and therefore inherits the constant’s name.
  • Three accesses are made: via instance, via class, and via interface.


Concept / Approach:
Static members should be accessed with a type name, but the language permits instance-qualified access as well (compiles, may elicit a warning). Since all three references point to the same compile-time constant, no runtime behavior beyond assignments occurs.


Step-by-Step Solution:
i = test141.k; → legal though stylistically discouraged; resolves to Foo141.k. i = Test141.k; → legal; Test141 inherits the constant from Foo141. i = Foo141.k; → canonical form; directly references the interface constant. No output, no exceptions.


Verification / Alternative check:
Mark k as something else (e.g., 5) and observe no behavioral change beyond assigned value; still compiles and runs.


Why Other Options Are Wrong:
There is no compilation error; there is nothing thrown at runtime since we only assign a primitive constant.


Common Pitfalls:
Believing interface fields are instance members; assuming instance-qualified access is illegal (it is legal but discouraged).


Final Answer:
Compiles and runs ok.

More Questions from Java.lang Class

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion