This code snippet demonstrates runtime polymorphism. Here’s why:
1. Polymorphism allows a method in a subclass to have the same name as a method in its superclass but behave differently. In this example, the printWeight() method is defined in both the PolarAnimal superclass and the Penguin subclass.
2. Method Overriding: The Penguin subclass overrides the printWeight() method of PolarAnimal. This means that if an object of Penguin is used to call printWeight(), it will execute the print("heavy") line instead of print("light") defined in the superclass.
3. Runtime Polymorphism (also known as dynamic polymorphism) happens at runtime, where the method to execute is determined based on the actual object type (i.e., whether it’s a Penguin or PolarAnimal instance) rather than at compile time.
Since printWeight() behaves differently in Penguin than in PolarAnimal, it demonstrates runtime polymorphism.
0 Comments:
Post a Comment