Java OCA OCP Practice Question 329

Question

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: } 
  • A. 2
  • B. 4
  • C. The code will not compile because of line 3.
  • D. The code will not compile because of line 5.
  • E. The code will not compile because of line 7.
  • F. The code will not compile because of line 11.
  • G. The output cannot be determined from the code provided.


C, D, E.

Note

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.




PreviousNext

Related