Polymorphism

- Sub-class can override superclass methods for any specific behavior implementation
- JVM dynamically calls appropriate method based on the inheritance hierarchy
- For the same method call the objects behave differently based on implementation
 
- Promotes reuse and design can be extended by adding more sub-classes without 
changing interface definition. Such as getLanguage() method in below example which takes Country as a parameter, so that it can be used for any Country type, such as Japan, America and Korea including any future new Countries. 
======================================================
Example: Polymorphism using method overriding

Description: Code to demonstrate polymorphic behavior in Java using inheritance and method overriding.


Country is superclass of all specific country sub-classes. The method getLanguage() can be overridden by sub-classes of Country class as shown below, where Japan and America are overriding default implementation of getLanguage() method from Country but Korea class is not overriding it. So when caller program (TestPoly) calls getLanguage() on the Country type the JVM will dynamically call appropriate 
getLanguage() method from sub-class, if method is not overridden in sub-class then JVM will call super class's method i.e. Method from Country in case of Korea.


Design: Class Diagram






Source: 

public class TestPoly {
    public static void main(String[] args) {
         Country[] countries = new Country[3];
         countries[0] = new Japan();
         countries[1] = new America();
         countries[2] = new Korea();    
         for (Country country : countries) {
              getCountryInfo(country);
         }
    }
    //method to print country specific information
    public static void getCountryInfo(Country country) {
         System.out.println(country.getLanguage());
    }
}
Output
Japan's National Language is Japanese
America's National Language is English
UN-KNOWN
--------------------------------------------------------
public class Country {   
     //default implementation
     protected String getLanguage() {
          return "UN-KNOWN";
     }
}
--------------------------------------------------------
public class Japan extends Country {   
     @Override
     public String getLanguage() {
          return "Japan's National Language is Japanese";
     }
}
--------------------------------------------------------
public class America extends Country {
     @Override
     public String getLanguage() {
          return "America's National Language is English";
      }
}
--------------------------------------------------------
public class Korea extends Country {


}

No comments :

Post a Comment