Java OCA OCP Practice Question 642

Question

Consider the following class and interface definitions in separate files:

public interface MyInterface{ 
     int v = 0; /*from   w w w.java  2  s. c  o  m*/
} 

public class Main implements MyInterface{ 
 public static void main (String [] args){ 
      Main s = new Main ();  //1 
      int j = s.v;           //2 
      int k = MyInterface.v; //3 
      int l = v;             //4 
  } 
} 

What will happen when the above code is compiled and run?

Select 1 option

  • A. It will give an error at compile time at line // 1.
  • B. It will give an error at compile time at line //2.
  • C. It will give an error at compile time at line //3
  • D. It will give an error at compile time at line //4.
  • E. It will compile and run without any problem.


Correct Option is  : E

Note

The fields defined in an interface are public, static, and final.

The methods are public and abstract.

Here, the interface MyInterface defines 'v' and thus any class that implements this interface inherits this field.

Therefore, it can be accessed using s.v or just 'v' inside the class.

Also, since it is static, it can also be accessed using MyInterface.v or Main.v.




PreviousNext

Related