Java OCA OCP Practice Question 1830

Question

What, if anything, is wrong with the following code?

// Filename: Main.java
class Main implements T1, T2{
   public void m1 (){}
}
interface T1{//from  w ww. ja v a 2s . c  om
   int V = 1;
   void m1 ();
}
interface T2{
   int V = 2;
   void m1 ();
}

Select 1 option

  • A. Main cannot implement them both because it leads to ambiguity.
  • B. There is nothing wrong with the code.
  • C. The code will work fine only if V is removed from one of the interfaces.
  • D. The code will work fine only if m1 () is removed from one of the interfaces.
  • E. None of the above.


Correct Option is  : B

Note

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

So you cannot call : System.out.println (V);

because it will be ambiguous (there are two V definitions).

But the following lines are valid :.

Main tc = new Main ();
System.out.println ((  ( T1) tc).V);

However, explicit cast is not required for calling the method m1():((T2)tc).m1();

tc.m1 () is also fine because even though m1 () is declared in both the interfaces, the definition to both resolves unambiguously to only one m1 (), which is defined in Main.




PreviousNext

Related