To explain what is an interface I will take some real world examples.

Imagine a IT company has two departments such billing module development sector and client details development sector. Billing module development sector will need to hide their API class implementation from client module developers. Therefore what they have to do is creating an interface and implement the real methods behaviors at implemented classed. And client module developers will be able to access interfaces only.

Public interface BillingClients{
double generateInterest(double rate, int numOfYears);
double netIncome(double totalRevenue, double taxPay)

Now if client department need to write software for Mc Donald’s then code will be look like below.

Public class BillingMcDonald() implements BillingClients{
      double generateInterest(double rate, int numOfYears){
             //calculate rate with number of years.
             return interest;

Default methods in Interface
Default method allows adding new functionality to interface without changing interface implemented classes. Old classes who has implemented from so called interface will no need to be updated since advantage of default method.
Example :-

public interface TimeClient {
    void setTime(int hour, int minute, int second);
    static ZoneId getZoneId (String zoneString) {
        try {
            return ZoneId.of(zoneString);
        } catch (DateTimeException e) {
            System.err.println("Invalid time zone: " + zoneString +
                "; using default time zone instead.");
            return ZoneId.systemDefault();
    default ZonedDateTime getZonedDateTime(String zoneString) {
        return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));

I’m explaining more about default methods and interface contains default method at below blog. You can read it if you need to know more about default method and its behavior.
When to use Interfaces

  1. When you want to implement external classes which are not related.
  2. Achieve multiple inheritance.

Compare interface with Abstract Class

Abstract Class Interface
Can have methods with or without implementations. Cannot have method implementations
Can declare fields as non-static and final. All fields are by default public, static and final
Can declare  public, protected and private concrete method All methods are by default public
Can extend by only one class but multiple interfaces.

One thought on “Interfaces in Java 01

Leave a Reply

Your email address will not be published. Required fields are marked *

WP Facebook Auto Publish Powered By :