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

Fields in Java are not polymorphic - they bind to the declared type (Mammal), so m.name returns 'furry '. Methods ARE polymorphic and use the actual object type (Zebra), so m.makeNoise() returns 'bray'. This is a key distinction between field access and method invocation in Java's inheritance model. Even though the object is a Zebra, field access is determined at compile time based on the reference type.

AI explanation

To determine the result of the given code, let's go through each option:

Option A) furry bray - This option concatenates the name variable from the Mammal class, which is "furry", with the result of the makeNoise() method from the Zebra class, which is "bray".

Option B) stripes bray - This option concatenates the name variable from the Zebra class, which is "stripes", with the result of the makeNoise() method from the Zebra class, which is "bray". However, the name variable in the Mammal class is not used.

Option C) furry generic noise - This option concatenates the name variable from the Mammal class, which is "furry", with the result of the makeNoise() method from the Mammal class, which is "generic noise".

Option D) stripes generic noise - This option concatenates the name variable from the Zebra class, which is "stripes", with the result of the makeNoise() method from the Mammal class, which is "generic noise".

Option E) Compilation fails - There are no compilation errors in the given code, so this option is incorrect.

Option F) An exception is thrown at runtime - There are no exceptions thrown in the given code, so this option is incorrect.

The correct answer is Option A) furry bray. This option is correct because it correctly combines the name variable from the Mammal class with the result of the makeNoise() method from the Zebra class.