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.

Post a Comment