Java OCA OCP Practice Question 1041

Question

What is the result of the following code?

1: public abstract class Shape { 
2:   private void fly() { System.out.println("Shape is flying"); } 
3:   public static void main(String[] args) { 
4:     Shape bird = new Rectangle(); 
5:     bird.fly(); /* w  w  w  . ja  v a  2  s.c o m*/
6:   } 
7: } 
8: class Rectangle extends Shape { 
9:   protected void fly() { System.out.println("Rectangle is flying"); } 
10: } 
  • A. Shape is flying
  • B. Rectangle is flying
  • C. The code will not compile because of line 4.
  • D. The code will not compile because of line 5.
  • E. The code will not compile because of line 9.


A.

Note

The code compiles and runs without issue, so options C, D, and E are incorrect.

The trick here is that the method fly() is marked as private in the parent class Shape, which means it may only be hidden, not overridden.

With hidden methods, the specific method used depends on where it is referenced.

Since it is referenced within the Shape class, the method declared on line 2 was used, and option A is correct.

Alternatively, if the method was referenced within the Rectangle class, or if the method in the parent class was marked as protected and overridden in the subclass, then the method on line 9 would have been used.




PreviousNext

Related