Explore core differences and applications of polymorphism in programming, focusing on compile-time and runtime forms. This quiz sharpens your understanding of method overloading, overriding, and their practical implications in object-oriented design.
Which of the following is an example of compile-time polymorphism in object-oriented programming?
Explanation: Method overloading allows multiple methods with the same name but different signatures in a class and is resolved during compilation, making it a classic example of compile-time polymorphism. Dynamic dispatch is related to runtime polymorphism, not compile-time. Method hiding is a concept related to variable or static method hiding and operates differently. Constructor chaining involves calling one constructor from another, but it is not an example of polymorphism.
When an overridden method is called through a base class reference pointing to a derived class object, which type of polymorphism is being demonstrated?
Explanation: This scenario shows runtime polymorphism, where the method implementation is determined at runtime through dynamic method dispatch. Compile-time polymorphism resolves the method call during compilation, which is not the case here. Static binding and early binding both refer to compile-time determination, which does not apply when using overridden methods in this manner.
Suppose you need to allow a class to have multiple ways to perform a calculation, each accepting different parameter types or counts. Which feature should you use?
Explanation: Method overloading lets you define several methods with the same name but different parameter lists within the same class, handling various calculation scenarios. Method overriding involves redefining a method in a subclass, not within the same class. Dynamic typing is not directly related to this feature. Abstract methods are intended for enforcement of method implementation in subclasses, not for changing parameter types or counts.
What does 'late binding' refer to in the context of polymorphism?
Explanation: Late binding is the process of resolving which method implementation to use during runtime rather than compile time, which is essential for runtime polymorphism. Selecting methods at compile time is called early (or static) binding. Binding static variables and initialization of objects are separate concepts unrelated to method dispatch in polymorphism.
Why is runtime polymorphism essential for designing flexible and maintainable systems using inheritance?
Explanation: Runtime polymorphism makes code more flexible and maintainable by allowing operations to be performed on objects with varying types, selected dynamically at runtime. Compiler optimizations happen mainly in compile-time polymorphism and do not offer the same flexibility. Restricting subclass changes or enforcing the same implementation does not represent the power or purpose of runtime polymorphism.