Page 177 - CTS - CSA TP - Volume 2
P. 177
COMPUTER SOFTWARE APPLICATION - CITS
}
// Main class
public class VirtualMethodExample {
public static void main(String[] args) {
// Create instances of the base class and derived classes
Shape genericShape = new Shape();
Circle myCircle = new Circle();
Square mySquare = new Square();
// Demonstrate virtual method calls
genericShape.draw(); // Calls Shape’s draw method
myCircle.draw(); // Calls Circle’s overridden draw method
mySquare.draw(); // Calls Square’s overridden draw method
// Demonstrate polymorphism
Shape polymorphicShape;
polymorphicShape = myCircle; // Circle assigned to Shape reference
polymorphicShape.draw(); // Calls Circle’s overridden draw method
polymorphicShape = mySquare; // Square assigned to Shape reference
polymorphicShape.draw(); // Calls Square’s overridden draw method
}
}
Explanation:
1 Base Class (Shape):
• Defines a virtual method draw that serves as a generic drawing method.
2 Derived Classes (Circle and Square):
• Extend the Shape class.
• Override the virtual method draw with specific implementations for drawing a circle and a square.
3 Main Class (VirtualMethodExample):
• Creates instances of the base class and derived classes.
• Demonstrates virtual method calls for each instance.
• Illustrates polymorphism by assigning instances of derived classes to a Shape reference and invoking
overridden methods.
In this example, the virtual method draw is overridden in the derived classes (Circle and Square). When an object
is assigned to a reference of the base class (Shape), the appropriate overridden method is called at runtime
based on the actual object type. This showcases the concept of virtual methods and polymorphism in Java.
Output:
162
CITS : IT & ITES - Computer Software Application - Exercise 109