1z0-808 Exam QuestionsBrowse all questions from this exam

1z0-808 Exam - Question 182


Given the definitions of the Bird class and the Peacock class:

and the code fragment:

Which code snippet can be inserted to print Fly.Dance. ?

Show Answer
Correct Answer: BD

To achieve the desired output where both methods from the Bird and Peacock classes are invoked correctly, the object must first be created as a Peacock to ensure that its methods are available. Then, it is cast back to a Peacock to allow direct method calls specific to the Peacock class. Hence, the correct code snippet is: Bird b = new Peacock(); Peacock p = (Peacock) b; This allows p to access both the fly() method from Bird and the dance() method from Peacock, resulting in the output 'Fly.Dance.'.

Discussion

8 comments
Sign in to comment
alex_auOption: D
Oct 9, 2022

Correct answer is D. For option B there is ClassCastException as class Bird cannot be casted to class Peacock

UAK94Option: D
Oct 14, 2022

Answer is D. class Bird{ public void fly() { System.out.println("fly"); } } public class Peacock extends Bird { public void dance() { System.out.println("dance"); } public static void main(String[] args) { Bird b= new Peacock(); Peacock p= (Peacock) b; // Bird b= new Bird(); // Peacock p= (Peacock) b; // ClassCastException p.fly(); p.dance(); } }

carlosworkOption: D
Oct 26, 2022

Tested. Answer is D. To test: class Bird { public void fly() { System.out.print("Fly."); } } class Peacock extends Bird { public void dance() { System.out.print("Dance."); } } public class Test { public static void main(String[] args) { Bird b = new Peacock (); Peacock p = (Peacock) b; p.fly(); p.dance(); } }

amigo31Option: D
Nov 19, 2022

I tested it. For B option is taken cast exception. D option worked correctly..

Drift_KingOption: D
Sep 13, 2023

Tested. Answer is - D. Bird b = new Peacock (); Peacock p = (Peacock) b;

iSnoverOption: B
Oct 9, 2022

The correct answer is the letter B, you need to create an object B and then do a casting for it, making the same be able to access the method of the child class.

Drift_King
Sep 13, 2023

You're are wrong. Correct answer is D. Option B is not how downcasting works. Option D is the textbook definition of downcating. With option our object type is peacock and class type of reference variable is also Peacock and peacock is a child class. Child class peacock can access it's method as well as Parent class Bird method.

Drift_King
Sep 13, 2023

*With option D

7df49fbOption: D
Mar 21, 2024

only D

BelloMioOption: D
Jun 5, 2024

It's not B because with Bird B = new Bird() and peacock p = (peacock) B; it's as if this becomes peacock p = new bird(); which is wrong