Exam 1z0-808 All QuestionsBrowse all questions from this 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. ?

    Correct Answer: D

    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
alex_auOption: D

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

carlosworkOption: D

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(); } }

UAK94Option: D

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(); } }

Drift_KingOption: D

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

amigo31Option: D

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

BelloMioOption: D

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

7df49fbOption: D

only D

iSnoverOption: B

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

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

*With option D