‹ Back to the paper
Answer the following questions related to object-oriented programming: In Java, polymorphism is…
Answer the following questions related to object-oriented programming:
(a)[2.0]
In Java, polymorphism is exhibited in two different ways. Identify them in the code snippets given in Column A and Column B?
| Column A | Column B |
|---|---|
| `Shapes myShape = new Shapes();`<br>`myShape.area();`<br>`myShape.area(5);`<br>`myShape.area(6.0, 1.2);`<br>`myShape.area(6, 2);` | `class Vehicle {`<br>` void drive() { System.out.println("Vehicle is moving"); }`<br>`}`<br>`class Bus extends Vehicle {`<br>` void drive() { System.out.println("Bus is running safely"); }`<br>`}`<br>`public static void main() {`<br>` Bus b = new Bus();`<br>` b.drive();`<br>`}` |
(b)[1.5]
Differentiate between the keywords `this` and `super(...)` with respect to constructor.
(c)[1.5]
Base class Student and derived class ICSEStudent are illustrated as: Student $\rightarrow$ ICSEStudent. Similarly, show the classes Shapes, Triangle, TwoD_Shapes, Sphere, ThreeD_Shapes exhibiting inheritance at multi-levels, depending on the type of shapes.
Answer
Answer (a)
AIColumn A shows compile-time (static) polymorphism / method overloading: the class Shapes has several area() methods with the same name but different parameter lists (no arguments, one int, two doubles, two ints), and the correct one is chosen at compile time based on the arguments passed.
Column B shows run-time (dynamic) polymorphism / method overriding: Bus overrides Vehicle's drive() method, and calling b.drive() on a Bus object invokes Bus's version - the method that actually runs is decided at run time based on the object's actual class.
Answer (b)
AIthis(...) is used inside a constructor to call another constructor of the same class (constructor chaining within the class), and must be the first statement in the constructor.
super(...) is used inside a constructor to call a constructor of the immediate base (parent) class, so the base class part of the object is initialised first; it must also be the first statement in the constructor.
Answer (c)
AIShapes -> TwoD_Shapes -> Triangle (one branch, for two-dimensional shapes)
Shapes -> ThreeD_Shapes -> Sphere (another branch, for three-dimensional shapes)
Both branches show multilevel inheritance, similar to Student -> ICSEStudent.
From ISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024), question 66.