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

COMPUTER SOFTWARE APPLICATION - CITS



           EXERCISE 109 : Create and use virtual methods



            Objectives


           At the end of this exercise you shall be able to
           •  develop Java programs to Create and use virtual methods.

           Requirements


           Tools/Materials
           •  PC / laptop with windows OS
           •   SDK software
           •  Test editor (Visual studio/ subline/ notepad)

           Procedure

           In Java, the term “virtual methods” is often associated with polymorphism, specifically dynamic method dispatch,
           which is a key feature of object-oriented programming (OOP). In Java, all non-static methods are inherently virtual.
           Let’s create a simple Java program that demonstrates the use of virtual methods and provide an explanation:
           // Base class
           class Shape {

               // Virtual method
               public void draw() {
                   System.out.println(“Drawing a generic shape”);
               }
           }



           // Derived class 1
           class Circle extends Shape {
               // Overrides the virtual method
               @Override

               public void draw() {
                   System.out.println(“Drawing a circle”);
               }
           }



           // Derived class 2
           class Square extends Shape {
               // Overrides the virtual method
               @Override

               public void draw() {
                   System.out.println(“Drawing a square”);
               }



                                                           161
   171   172   173   174   175   176   177   178   179   180   181