Java interface

Java interface

Java Interface

Interface is used to achieve full abstraction in java. Interface basically is a prototype or a contract – whatever is written in contract must be implemented. In this tutorial, we will discuss about interface, loose coupling, tight coupling, interface example and much more.

Java interface



What is interface

Let’s understand what is interface with real world example:

ABC is a training institute which provides training to different organizations. A Company hired a number of freshers for their upcoming project but they are looking for a training provider who can train their employees. So, Company contacts ABC institute for training purpose.

ABC institute prepares a prototype or contract and presents to the company. Company reads the contract whatever written in the contract and company finds it suitable. So they both agree and sign on the contract.

ABC company will have to follow whatever is written in the contract.

Same happens in the case of interface. You prepare a prototype or contract by using an interface in java. Then, any class which is implementing that interface will have to follow what is written inside that interface. That class will have to write definition for all of it’s methods.

Basic syntax

interface InterfaceName {
     public void methodName();
}

Interface can be implemented by using “interface” keyword in java. An interface implements full abstraction, so you can only declare methods but you can not define them. The class which is implementing the interface will have to provide definition to all of it’s methods.

Some important things to remember about an interface

  1. You can create an interface by using “interface” keyword.
  2. An interface can only contain abstract methods which are public abstract by default (Up to java 1.7).
  3. An interface can only contain constant variables, means all variables in interface are public static final by default.
  4. An interface can extend another interface by simply using “extends” keyword.
  5. A Class can implement any number of interfaces at a time by simply using “implements” keyword.
  6. You can not use static, final or any other non access modifier with methods in interface (In java 8, you can create static methods).
  7. You can only create public static final variables inside any interface.
  8. An interface without any declaration is called marker interface.
  9. An interface is widely used in the concept of loose coupling and becoming popular while writing frameworks.
  10. You can not create object on an interface just like abstract class.

Simple Interface Example

We will create a basic example by using interface. 

interface UserLogin {
     public String LOGIN_MESSAGE = "Please login";
     public String LOGOUT_MESSAGE = "You have been logged out successfully.";
     public String login();
     public String logout();
}

class UserLoginImpl implements UserLogin {

     public String login() {
         return LOGIN_MESSAGE;
     }

     public String logout() {
         return LOGOUT_MESSAGE;
     }
}

class Demo {

     public static void main(String arg[]) {

       UserLoginImpl user = new UserLoginImpl();
       System.out.println(user.login());
       System.out.println(user.logout());
     }
}

Look at the above example, where we have an interface “UserLogin” with some constant variables and abstract methods. Then UserLoginImpl class is implementing that particular interface. UserLoginImpl will have to provide the definition to all of it’s methods.

Now let’s understand the concept tight coupling and how to overcome it by interface

We will understand the term tight coupling with a simple example as below. Suppose, you have two classes as below.

class Trip { 
      private Car car;

      public Trip() {
          car = new Car(); // Tight coupling
      }

      public void startTrip() {
          car.start();
      }
}

class Car {
      public void start() {
          System.out.println("Car is moving now..");
      }
}


In above example, we have two classes Trip and Car. The purpose of trip class is to represent trip and Car class represents vehicle.

Generally, Trip is dependent upon vehicle. Without a vehicle, a trip is not possible. That’s why an object of type Car is created inside Trip class. Trip has a method startTrip() in which method of car is being called to start the trip.

Now, how Car is tightly coupled here? As you can see above, an object of car type is being created inside constructor of Trip class. Suppose, you don’t want to start your trip from car, you want to go from bike. What will happen now, you will have to create another object of bike class inside trip class and so on.

Each and every time, you will have to create an object of different vehicle to start you trip. At one stage, it will become complex for you to maintain and there will be more dependency in a single class.

Interface is the only solution (loose coupling)

So, how can we overcome from the above problem? By simply using interface. But how? So, let’s modify above example with a little mixture of interface.

interface Vehicle {
      public void start();
}

class Car implements Vehicle {
      public void start() {
         System.out.println("Starting my trip from car.");
      }
}

class Bike implements Vehicle {
      public void start() {
         System.out.println("Starting my trip from bike.");
      }
}

class Trip {
      private Vehicle v;
 
      public void setVehicle(Vehicle v) {
         this.v = v;
      }

      public void startTrip() {
         this.v.start();
      }
}

class Demo {

      public static void main(String arg[]) {

         Trip t = new Trip();
 
         t.setVehicle(new Car());
         t.startTrip();

         t.setVehicle(new Bike());
         t.startTrip();
      }
}

Now see the power of interface, Trip class is not tightly coupled with vehicle. You can now plan your trip from any vehicle. You can create any number of vehicle class, you just need to implement vehicle interface. After that you can pass that vehicle to the setVehicle() method of Trip class and your trip will begin.

What is marker interface

Market interface is nothing but a blank interface without any method or variable declaration. The purpose of making marker interface is just to mark a particular class for purpose. Like Serializable marker interface, this tells JVM that particular class can be serialized.

Syntax

interface MarkIt { }

Related Post

Leave a Reply

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