Java OCA OCP Practice Question 1258

Question

How many changes need to be made to the classes below to properly override the watch() method?

package mypkg; 
class TV { 
        protected final void watch() {} 
} 
public class LCD extends TV { 
        Object watch() {} 
} 
  • A. One
  • B. Two
  • C. Three
  • D. None; the code compiles as is.


C.

Note

There are three problems with this method override.

The watch() method is marked final in the TV class.

The final modifier would have to be removed from the method definition in the TV class in order for the method to compile in the LCD class.

The return types void and Object are not covariant.

One of them would have to be changed for the override to be compatible.

The access modifier in the child class must be the same or broader than in the parent class.

Since package-private is narrower than protected, the code will not compile.

Option C is the correct answer.




PreviousNext

Related