Page 381 - Computer_Science_F5
P. 381

Computer Science  the superclass. Subclasses can redefine (override) inherited methods to offer their
           unique implementations, facilitating polymorphic behavior.

                    Program Example 5.36:

          FOR ONLINE READING ONLY
             Java program to demonstrate polymorphism
               class Animal {
                   public void makeSound() {
                       System.out.println(“Animal makes different sounds”);
                   }
               }
               class Lion extends Animal {
                   //This method override
                   public void makeSound() {
                       System.out.println(“ Lion roars”);
                   }
               }
               class Cat extends Animal {
                   //This method override
                   public void makeSound() {
                       System.out.println(“Cat meows”);
                   }
               }
               public class Main {
                   public static void main(String[] args) {
                       Animal myFirstAnimal = new Lion();
                       Animal mySecondAnimal = new Cat();


                       myFirstAnimal.makeSound(); // This method will print “Lion roars”
                       mySecondAnimal.makeSound(); // This method will print “Cat meows”
                   }
               }



           In Java, polymorphism  is achieved  through  inheritance,  method  overriding,  and
           method overloading.



              Activity 5.12:

             Visualisation of polymorphism in Java
            Use Jeliot 3 or later version, visualise the step by step execution of java program
            to explore about polymorphism in Java. Use the code in Program Example 5.39.


                                                 372
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   372                                                     23/07/2024   12:34
   376   377   378   379   380   381   382   383   384   385   386