Oracle Certified Associate Java Se 8 Programmer · Free Practice Question Hard
Question 13
What will be the result of compiling and executing Circus
- //Circus.java
- package com.udayan.oca;
- class Animal {
- protected void jump() {
- System.out.println("Animal");
- }
- }
- class Cat extends Animal {
- public void jump(int a) {
- System.out.println("Cat");
- }
- }
- class Deer extends Animal {
- public void jump() {
- System.out.println("Deer");
- }
- }
- public class Circus {
- public static void main(String[] args) {
- Animal cat = new Cat();
- Animal deer = new Deer();
- cat.jump();
- deer.jump();
- }
- }
-
A
Cat
Deer -
B
Cat
Animal -
C
Animal
Deer -
D
Animal
Animal
Reveal correct answer
Correct answer: C
Explanation
Cat class doesn't override the jump() method of Animal class, in fact jump(int) method is overloaded in Cat class.
Deer class overrides jump() method of Animal class.
Reference variable cat is of Animal type, cat.jump() syntax is fine and as Cat doesn't override jump() method hence Animal version is invoked, which prints Animal to the console.
Even though reference variable deer is of Animal type but at runtime deer.jump(); invokes overriding method of Deer class, this prints Deer to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
