Java OCA OCP Practice Question 1526

Question

What will be the output of compiling and running the following program:

public class Main implements Interface1, Interface2 {
   public void m1() {
      System.out.println("Hello");
   }//from  w  w  w  .  ja  v  a 2s.  c o  m

   public static void main(String[] args) {
      Main tc = new Main();
      ((Interface1) tc).m1();
   }
}

interface Interface1 {
   int VALUE = 1;

   void m1();
}

interface Interface2 {
   int VALUE = 2;

   void m1();
}

Select 1 option

  • A. It will print Hello.
  • B. There is no way to access any VALUE in Main.
  • C. The code will work fine only if VALUE is removed from one of the interfaces.
  • D. It will not compile.
  • E. None of the above.


Correct Option is  : A

Note

Having ambiguous fields does not cause any problems but referring to such fields in an ambiguous way will cause a compile time error.

So you cannot call: System.out.println (VALUE) as it will be ambiguous.

as there is no ambiguity in referring the field:

Main tc = new Main (); 
System.out.println ((  ( Interface1) tc).VALUE); 

So, any of the VALUE fields can be accessed by casting.




PreviousNext

Related