Which of the following best explains why polymorphism is needed in Java programming?
Think about how polymorphism helps when you want to write code that works with many types of objects in a uniform way.
Polymorphism allows a single interface to represent different underlying forms (data types). This means you can write code that works on the superclass type but actually operates on subclass objects, making code more flexible and reusable.
What is the output of the following Java code?
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } public class Test { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
Remember that the actual method called depends on the object's runtime type, not the reference type.
The variable 'a' is of type Animal but refers to a Dog object. The overridden method sound() in Dog is called, so it prints "Bark".
What error will this Java code produce and why?
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { void sound(int volume) { System.out.println("Bark at volume " + volume); } } public class Test { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
Check if the Dog class actually overrides the sound() method with no parameters.
The Dog class defines sound(int volume), which is an overload, not an override of sound(). So the call a.sound() calls Animal's sound() method, printing "Animal sound".
Which of the following Java code snippets correctly uses polymorphism to call the overridden method?
Remember polymorphism works when a superclass reference points to a subclass object.
Option B shows a superclass reference 'a' pointing to a subclass object 'new Dog()'. Calling a.sound() invokes Dog's overridden method if it exists.
Consider a program that processes different types of payment methods: CreditCard, PayPal, and Bitcoin. Which statement best explains how polymorphism helps in extending this program?
Think about how polymorphism supports adding new types without modifying existing code.
Polymorphism allows the program to treat all payment methods uniformly through a common interface or superclass. New payment types can be added without changing the code that processes payments, improving extensibility.