Multiple choice technology web technology

Given: 3. class Mammal { 4. String name = "furry "; 5. String makeNoise() { return "generic noise"; } 6. } 7. class Zebra extends Mammal { 8. String name = "stripes "; 9. String makeNoise() { return "bray"; } 10. } 11. public class ZooKeeper { 12. public static void main(String[] args) { new ZooKeeper().go(); } 13. void go() { 14. Mammal m = new Zebra(); 15. System.out.println(m.name + m.makeNoise()); 16. } 17. } What is the result?

  1. furry bray

  2. stripes bray

  3. furry generic noise

  4. stripes generic noise

  5. Compilation fails

  6. An exception is thrown at runtime

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

Field access in Java is bound at compile-time based on the reference type, not the actual object type. The variable m is declared as Mammal, so m.name refers to Mammal's 'furry' field. However, method calls are polymorphic - makeNoise() invokes Zebra's overridden method returning 'bray'.

AI explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) furry bray - This option is the correct answer. The code creates an instance of the ZooKeeper class and calls the go() method. Inside the go() method, a new Zebra object is created and assigned to a Mammal reference variable m. When we call m.name, it refers to the name variable in the Mammal class, which is "furry". When we call m.makeNoise(), it invokes the makeNoise() method in the Zebra class, which returns "bray". Therefore, the output will be "furry bray".

Option B) stripes bray - This option is incorrect because m.name refers to the name variable in the Mammal class, which is "furry", not "stripes".

Option C) furry generic noise - This option is incorrect because m.makeNoise() invokes the makeNoise() method in the Zebra class, which returns "bray", not "generic noise".

Option D) stripes generic noise - This option is incorrect because m.name refers to the name variable in the Mammal class, which is "furry", not "stripes". Additionally, m.makeNoise() invokes the makeNoise() method in the Zebra class, which returns "bray", not "generic noise".

Option E) Compilation fails - This option is incorrect. The code compiles successfully without any compilation errors.

Option F) An exception is thrown at runtime - This option is incorrect. The code does not throw any exceptions at runtime.

The correct answer is Option A) furry bray. This option is correct because it correctly represents the output of the code snippet.