What is the output of the following code? (Choose all that apply)
1: interface HasArea { int getArea(); } 2: abstract class Rectangle implements HasArea { 3: protected int getArea() {return 4;} 4: } //from w w w . jav a 2 s . c o m 5: public class Square extends Rectangle { 6: public static void main(String[] args) { 7: Rectangle r = new Rectangle(); 8: System.out.println(r.getArea()); 9: } 10: 11: public int getArea(int length) {return 2;} 12: }
C, D, E.
First, the method getArea()
in the interface HasArea
is assumed to be public, since it is part of an interface.
The implementation of the method on line 3 is therefore an invalid override, as protected is a more restrictive access modifier than public, so option C is correct.
Next, the class Square implements an overloaded version of getArea()
, but since the declaration in the parent class Rectangle is invalid, it needs to implement a public version of the method.
Since it does not, the declaration of Rectangle is invalid, so option D is correct.
Option E is incorrect, since Rectangle is marked abstract and cannot be instantiated.
The overloaded method on line 11 is declared correctly, so option F is not correct.
Finally, as the code has multiple compiler errors, options A, B, and G can be eliminated.