Page 143 - CTS - CSA TP - Volume 2
P. 143

COMPUTER SOFTWARE APPLICATION - CITS




           public class ShapeDemo {
           public static void main(String[] args) {

           Shape shape1 = new Circle();
           shape1.draw(); // Output: Drawing a circle
           Shape shape2 = new Rectangle();
           shape2.draw(); // Output: Drawing a rectangle

           }
           }
           Output:












           Explanation:
           •  In this program, we have a superclass Shape and two subclasses Circle and Rectangle.
           •  The Shape class has a method named draw() that prints “Drawing a shape”.

           •  Both Circle and Rectangle classes extend the Shape class and override the draw() method with their own
              specific implementations.
           •  In the ShapeDemo class, we create instances of Circle and Rectangle and assign them to references of
              type Shape.
           •  When we call the draw() method on each object, the overridden version of the method is invoked based on
              the actual object type, demonstrating dynamic dispatch.
           •  Method overriding allows us to provide specialized implementations of methods in subclasses, promoting
              code reusability and polymorphic behavior.



           TASK 2: Animal and its Subclasses
           // Method overriding
           class Animal {
           void sound() {
           System.out.println(“Animal makes a sound”);

           }
           }
           class Dog extends Animal {
           // Overriding the sound method of the superclass

           @Override
           void sound() {
           System.out.println(“Dog barks”);
           }
           }



                                                           128
                                CITS : IT & ITES - Computer Software Application - Exercise 99
   138   139   140   141   142   143   144   145   146   147   148