Static Polymorphism in Java with Program

Static Polymorphism, Static Binding, Compile time Polymorphism,
Method Overloading.


Polymorphism is one of the most important OOPS concept. The word "Polymorphism" means, "one name having many forms".

Please note, Polmorphism is just a concept that describes the ability of a method to behave differently at different situation, but is actually achieved either by Method Overloading(Static Polymorphism) or by Method Overriding(Dynamic Polymorphism).

More details on Polymorphism concept with example: here
 
Types of Polymorphism

  1. Static Polymorphism - Static Binding - Compile time Polymorphism - Method Overloading
  2. Dynamic Polymorphism - Dynamic Binding - Run time Polymorphism - Method Overriding  
Lets understand Static Polymorphism in more details with example.

What is Polymorphism in Java with example.

What is Polymorphism in Java with example.


Polymorphism is one of the most important OOPS concept that means "one name having many forms".

Polymorphism is Greek word which means "Many Forms", If we break the word, we will get,
Polymorphism = (Poly + Morphism) = Many + Forms.

 Lets understand above line in more details with example.

Interface example in Java

Interface example in Java with Program?


Interface is used in a situation,
  1. When you know the contract methods but don't know anything about the implementation.
  2. Your contract implementation can change in future.
  3. You want to achieve dynamic polymorphishm and loose coupling that is by just changing one line of code, you should be able to switch between contract implementer.
Lets understand above points in more details:


Interface example in Java.

When to use Interface and Abstract class with Real example: here
When to use Interface in Java: here

Example 1

Lets say we want to start a service like "makemytrip.com" or "expedia.com",  where we are responsible for displaying the flights from various flight service company and place an order from customer. 
Lets keep our service as simple as, 
  1. Displaying flights available from vendors like "AirIndia", "Emirates" and "JetAirways".
  2. Place and order for seat to respective vendor.
Remember, In this application, we don't own any flight. we are just a middle man/aggregator.
Lets see how to design it.

FlightService Interface
interface FlightService{
 void getAllFlights();
 void doBooking();
}
Emirates Implementation
class Emirates implements FlightService{
 @Override
 public void doBooking() {
  System.out.println("Do booking in Emirates way");
 }
 @Override
 public void getAllFlights() {
  System.out.println("Get flights in Emirates way");
 }
}
JetAirways Implementation
class JetAirways implements FlightService{
 @Override
 public void doBooking() {
  System.out.println("Do booking in JetAirways way");
 }
 @Override
 public void getAllFlights() {
  System.out.println("Get flights in JetAirways way");
 }
}

AirIndia Implementation
class AirIndia implements FlightService{
 @Override
 public void doBooking() {
  System.out.println("Do booking in AirIndia way");
 }
 @Override
 public void getAllFlights() {
  System.out.println("Get flights in AirIndia way");
 }
}

InterfaceTest.java

import java.util.ArrayList;
import java.util.List;

public class InterfaceTest {
 
 private static FlightManager flightManager = new FlightManager();
 
 public static void main(String[] args) {
  
  loadVendors();
  
  System.out.println("Get all flights...");
  for (FlightService fs: flightManager.getListVendors()) {
   fs.getAllFlights();
  }
  
  System.out.println("Do booking.");
  for (FlightService fs: flightManager.getListVendors()) {
   fs.doBooking();
  }
 }
 
 private static void loadVendors(){
  flightManager.addVendor(new Emirates());
  flightManager.addVendor(new AirIndia());
  flightManager.addVendor(new JetAirways());
 }
}
FlightManager.java
import java.util.ArrayList;
import java.util.List;

class FlightManager{
 private List<FlightService> listVendors = null;
 
 public FlightManager() {
  listVendors = new ArrayList<FlightService>();
 }
 
 public void addVendor(FlightService fs){
  this.listVendors.add(fs);
 }
 
 public List<FlightService> getListVendors() {
  return listVendors;
 }
 
}

Example 2

Lets say we have a requirement to Sort array but don't know which sorting algorithm to use because it depends on the nature of array.
  1. If the data set is small and nearly sorted then Insertion sort works well.  
  2. If we are working on big size array and have space constraint then Merge sort works very well.
So each sorting algorithm is fit for particular use cases.
How to design our sorting application which helps other application to sort integer array.

Sort.java
interface Sort{
 int[] sort(int[] arr);
}
MergeSort.java
class MergeSort implements Sort{
 @Override
 public int[] sort(int[] arr) {
  System.out.println("Sort array using Merge sort algorithm");
  return arr;
 }
}
InsertionSort.java
class InsertionSort implements Sort{
 @Override
 public int[] sort(int[] arr) {
  System.out.println("Sort array using Insertion sort algorithm");
  return arr;
 }
}
QuickSort.java
class QuickSort implements Sort{
 @Override
 public int[] sort(int[] arr) {
  System.out.println("Sort array using Quick sort algorithm");
  return arr;
 }
}
InterfaceTest.java
public class InterfaceTest {
 
 public static void main(String[] args) {
  int choice = 2; // user choice
  
  Sort sortObj = null;
  if(choice == 1){
   sortObj = new InsertionSort();
  
  }else if(choice == 2){
   sortObj = new QuickSort();
  
  }else if(choice == 3){
   sortObj = new MergeSort();
  }
  
  //common line used for all types of sorting
  //which algorithm will be called for sorting that depends on which object is passed to sortObj reference.
  sortObj.sort(new int[]{3,2,1}); 
 }
}

Example 3

Assume, you are writing a web service for Filtering data. 

Example: In Amazon.com, you can filter the product, By Color, By Material, By Brand, By Price and so on.
Similarly, assume your application also has such type of filtering where user can filter listing by multiple criteria. 
Also, application can be accessed by,
  1. Desktop browser which sends filter data in XML format.
    
       abc
       1000
       5000
       blue
    
  2. Mobile app which sends filter data in JSON format.
    {
      "filterData": {
        "brand": "abc",
        "priceFrom": "1000",
        "priceTill": "5000",
        "color": "blue"
      }
    }
    
How will you design your application in this scenario where user can provide input data in XML and JSON format. 
While designing application, think of future requirements as well, today there are 2 formats, tomorrow application clients can send data in multiple format like CSV etc, so handle those cases as well.
For this example, try to give a try by yourself. In case if you find difficulty in implementing, see below.
interface Parser{
 Object parse(String filterString);
}
class JSONParser implements Parser{
 @Override
 public Object parse(String filterString) {
  System.out.println("Parsing JSON string and returning Object");
  return null;
 }
}
class XMLParser implements Parser{
 @Override
 public Object parse(String filterString) {
  System.out.println("Parsing XML string and returning Object");
  return null;
 }
}
class CSVParser implements Parser{
 @Override
 public Object parse(String filterString) {
  System.out.println("Parsing CSV string and returning Object");
  return null;
 }
}

public class InterfaceTest {
 
 public static void main(String[] args) {
  
  String requestCameFrom = "mobile"; //request coming from
  String filterData = "null"; //Filter data coming from UI, can be XML, JSON, CSV etc.
  
  
  Parser parser = null;
  if(requestCameFrom.equals("mobile")){
   parser = new JSONParser();
  
  }else if(requestCameFrom.equals("desktop")){
   parser = new XMLParser();
  }
  
  parser.parse(filterData); 
 }
}

You may also like to see


When to use Interface in java with example

Interface Vs Abstract class in Java OOPS.

Top Java Interface Interview Questions and Answers

When to use interface and abstract class in Java? what is the difference between them?

Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

When to use Interface in java with example

When to use Interface in java with example?


Interface is used in a situation,
  1. When you know the contract methods but don't know anything about the implementation.
  2. Your contract implementation can change in future.
  3. You want to achieve dynamic polymorphishm and loose coupling that is by just changing one line of code, you should be able to switch between contract implementer.
Lets understand above points in more details:


Interface in Java.

When to use Interface and Abstract class with Real example: 
https://javabypatel.blogspot.com/2017/07/when-to-use-abstract-class-and-interface-difference-between-them.html

When you know the contract methods but don't know anything about the implementation

Lets say we want to start a service like "makemytrip.com" or "expedia.com",  where we are responsible for displaying the flights from various flight service company and place an order from customer. 
Lets keep our service as simple as, 
  1. Displaying flights available from vendors like "AirIndia", "Emirates" and "JetAirways".
  2. Place and order for seat to respective vendor.
Remember, In this application, we don't own any flight. we are just a middle man/aggregator and our task is to first enquire "AirIndia", then enquire "Emirates" and at last enquire "JetAirways" about the list of flights available and later if customer opts for booking then inform the respective flight vendor to do booking.


For this, first we need to tell "AirIndia", "Emirates" and "JetAirways" to give us list of flights, internally how they are giving the list that we don't care.
  1. This means I only care for method name "getAllFlights()"

    "getAllFlights()" from
    "AirIndia" may have used SOAP service to return list of flights.
    "getAllFlights()" from "Emirates" may have used REST service to return list of flights.
    "getAllFlights()" from
    "
    JetAirways" may have used CORBA service to return list of flights.

    but we don't care how it is internally implemented and what we care is the contract method "
    getAllFlights" that all the flight vendor should provide and return list of flights.

  2. Similarly, for booking I only care for method name "doBooking()" that all vendors should have, internally how this vendors are doing booking that I don't care.

To conclude: We know contract.
So we can say that we know the contract that irrespective of who the Flight vendor is, you need "getAllFlights()" and "doBooking()" method from them to run our aggregator service.

Your contract implementation can change in future. 
Say we want to develop some business application which require usage of Database and we choose to use Oracle. So we will design something like below,


We are using Oracle database and all our layers are binded to use OracleDatabaseManager to fetch data using Oracle database.

Now, say tomorrow we plan to change our database to Postgresql, We will end up changing all our layers, which is wrong. If we need to change all our layers, imagine testing and development efforts required. 

So how our design should be which can sustain future changes ? Interface will come to rescue.
Instead of using calling concrete implementation menthods in service layer, we should call contract methods of interface which doesn't know anything about implementation.

In this appraoch, Service layer doesn't care as which implementation we are using.
So in future if we switch from Oracle to PostgreSQL or to any vendor, Service layer will have no impact and it will remain as it is because it calls interface contract methods which doesn't care about implementation.

Only change required is in Database layer which is also a minimal change.
Also, this design helps us adding more vendor as an when required without disturbing the existing vendor implementation.


You want to achieve dynamic polymorphishm and loose coupling that is by just changing one line of code, you should be able to switch between contract implementer.

From above point, you can see, by only changing the middle layer, we are able to switch database implementation to different vendor without disturbing service layer.

So we can say that our application or our service layer is not tightly coupled with database layer instead both layer works on contract which make them loosely coupled and changes on one layer doesn't affect another layer as contract still remains same.

You may also like to see


Interface example in Java with Program

Interface Vs Abstract class in Java OOPS.

Top Java Interface Interview Questions and Answers

When to use interface and abstract class in Java? what is the difference between them?

Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.