Polymorphism


Polymorphism means “many forms,” and it occurs when we have many classes that are related to each other by inheritance. 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 Animal could be Pig, Cat, Dog, Bird — And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):

Polymorphism.java (polymorphism)
class Polymorphism {
  public static void main( String[ ] args ) { 
    if      ( args[0].equals( "Animal" ) ) {
      Animal myAnimal = new Animal( );
      myAnimal.animalSound( );
    }
    else if ( args[0].equals( "Dog"    ) ) {
      Animal myDog = new Dog( );
      myDog.animalSound( );
    }
    else if ( args[0].equals( "Pig"    ) ) {
      Animal myPig = new Pig( );
      myPig.animalSound( );
    }
  }
}
class Animal {
  public void animalSound( ) { System.out.print( "growl" ); }
}
class Dog extends Animal {
  public void animalSound( ) { System.out.print( "bow" ); }
}
class Pig extends Animal {
  public void animalSound( ) { System.out.print( "wee" ); }
}
shell> java Polymorphism  

Output:           Result:




      “The older I grow, the more I distrust the familiar doctrine    
      that age brings wisdom.”    
      ― H.L. Mencken