Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 27
Question ID: UKOCP32368
Consider below codes of 4 java files:
- //I1.java
- package com.udayankhattry.ocp;
- public interface I1 {
- int i = 10;
- }
- //I2.java
- package com.udayankhattry.ocp;
- public interface I2 {
- int i = 20;
- }
- //I3.java
- package com.udayankhattry.ocp;
- public interface I3 extends I1, I2 { //Line n1
- }
- //Test.java
- package com.udayankhattry.ocp;
- public class Test {
- public static void main(String[] args) {
- System.out.println(I1.i); //Line n2
- System.out.println(I2.i); //Line n3
- System.out.println(I3.i); //Line n4
- }
- }
Which of the following statements is correct?
- A Line n1 causes compilation error
- B Line n2 causes compilation error
- C Line n3 causes compilation error
- D Line n4 causes compilation error
- E There is no compilation error
Reveal correct answer
Correct answer: D
Explanation
UKOCP32368:
Variable 'i' declared inside interface I1 is implicitly public, static and final. Similarly, variable i declared inside interface I2 is implicitly public, static and final as well.
In Java, a class can extend from only one class but an interface can extend from multiple interfaces. static variables are not inherited and hence there is no issue with Line n1.
I1.i points to variable 'i' of interface I1.
I2.i points to variable 'i' of interface I2.
I3.i is an ambiguous call, as compiler is not sure whether to point to I1.i or I2.i and therefore, Line n4 causes compilation error.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
