Interface in Java

An interface is a collection of abstract Methods and static final(Constant) Variables.

The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.

interface interface_name{
   static final data_type variable_name;
   return_type method_name(parameter);
   return_type method_name(parameter);
}

Example:

interface Plane{
     void takeOff();
     void fly();
     void land();
}

class PassengerPlane implements Plane{
     public void takeOff(){
         System.out.println("plane is about takeoff");
     }
     public void fly(){
         System.out.println("plane is flying");
     }
     public void land(){
         System.out.println("plane landed");
     }
}

class PlaneDemo{
     public static void main(String args[]){
     //rest of the class statements 
     }
}

Here, in this example we have created Plane interface, which has three methods there are by default abstract. now, in PassengerPlane class we have implemented interface Plane so that we need to give the definition of all the methods which are present in Plane interface.

Note: Here, we need to remember one thing that object of n interface cannot be created and all the methods which are going to overridden should be declared as public in implemented class.

Tagged interface

An interface that has no member is known as marker or tagged interface. For example, Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.

//Way of writing Serializable interface  
public interface Serializable
{  
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: