Consider the follwing code:
1. interface Beta {}
2.
3. class Alpha implements Beta
{
4.
String testIt()
{
5. return �Tested�;
6. }
7. }
8.
9. public class Main1
{
10. static Beta getIt()
{
11. return new Alpha();
12. }
13.
public static void main( String[] args )
{
14. Beta b = getIt();
15. System.out.println( b.testIt() );
16. }
17. }
What is the result?
A. Tested
B. Compilation fails.
C. The code runs with no output.
D. An exception is thrown at runtime.
Answer: B
On compiling, I got:
C:\>javac Main1.java
Main1.java:20: cannot resolve symbol
symbol : method testIt ()
location: interface Beta
System.out.println( b.testIt() );
1 error
Now, my question is:
what method is invoked when the compiler comes across the statement b.testIt(); As far as I understand, method invocation for non-static methods depends on the class of the reference variable at runtime, which in this case, I believe, is Alpha (since the method getIt actually returns an Alpha object - return new Alpha());