Page 402 - CITS - Computer Software Application -TT
P. 402

COMPUTER SOFTWARE APPLICATION - CITS

            Polymorphism in Java


           Polymorphism means “many forms”, and it occurs when we have many classes that are related to each other by
           inheritance.
           Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class.
           Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different
           ways.
           For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals
           could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks,
           and the cat meows, etc.):
           Example

           Get your own Java Server
           class Animal {
           public void animalSound() {
           System.out.println(“The animal makes a sound”);
           }
           }

           class Pig extends Animal {
           public void animalSound() {
           System.out.println(“The pig says: wee wee”);
           }

           }
           class Dog extends Animal {
           public void animalSound() {
           System.out.println(“The dog says: bow wow”);
           }

           }

            Creating, Implementing And Extending Interfaces


           An interface in Java is syntactically similar to a class but can have only abstract methods declaration and constants
           as members.

           In other words, an interface is a collection of abstract methods and constants (i.e. static and final fields). It is used
           to achieve complete abstraction.
           Every interface in Java is abstract by default. So, it is not compulsory to write abstract keyword with an interface.
           Once  an  interface  is  defined,  we  can  create  any  number  of  separate  classes  and  can  provide  their  own
           implementation for all the abstract methods defined by an interface.
           A class that implements  an interface is called  implementation class. A class can implement  any number  of
           interfaces in Java. Every implementation class can have its own implementation for abstract methods specified in
           the interface as shown in the below figure














                                                           389

 CITS : IT&ITES - Computer Software Application - Lesson 109 - 115  CITS : IT&ITES - Computer Software Application - Lesson 109 - 115
   397   398   399   400   401   402   403   404   405   406   407