What is polymorphism in Java?
A
When a class inherits another
B
When one method behaves differently based on context
C
When a class has no body
D
When objects are converted to strings
Analysis & Theory
Polymorphism allows one method or object to take many forms depending on context.
Which of the following is an example of compile-time polymorphism?
B
Interface implementation
Analysis & Theory
Method overloading is resolved at compile time, so it's an example of compile-time polymorphism.
Which concept allows a subclass to provide a specific implementation of a method already defined in its superclass?
Analysis & Theory
Method overriding enables runtime polymorphism by redefining methods in a subclass.
What is the output?
```java
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}```
Analysis & Theory
Since `a` refers to a `Dog` object, the overridden `sound()` method in `Dog` is executed.
What is the output?
```java
class MathOp {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
class Main {
public static void main(String[] args) {
MathOp m = new MathOp();
System.out.println(m.add(2, 3));
}
}```
Analysis & Theory
The `add(int, int)` method is called and returns 2 + 3 = 5.
Which of the following supports runtime polymorphism?
A
Constructor overloading
Analysis & Theory
Method overriding is determined at runtime based on the object's actual class.
Can you override a static method in Java?
B
Yes, with the `super` keyword
C
No, static methods belong to the class, not instance
D
Only in abstract classes
Analysis & Theory
Static methods cannot be overridden because they are bound to the class, not the object.
What is required for method overriding?
A
Same method name, same parameter list, and same class
B
Same method name and same class
C
Same method name and parameter list in subclass
D
Different method name in subclass
Analysis & Theory
For method overriding, the subclass must define a method with the exact same signature as in the superclass.
Which of the following is true about method overloading?
A
It can change return type only
B
It must change method name
C
It must differ in parameter list
D
It requires inheritance
Analysis & Theory
Method overloading requires a different parameter list (number or type), but same method name.
What is dynamic method dispatch?
A
Calling a method in a static way
B
Deciding the method to call at compile time
C
Process of resolving overridden method at runtime
D
Invoking private methods
Analysis & Theory
Dynamic method dispatch resolves which overridden method to call at runtime based on the object.