Interface is definition of set of actions that an object of particular type can do. Interface is group of related abstract methods. Interface also may contain fields. Interface contains method declarations. Constructors are not there in interface so interface can not be used to create instances.

Defining interface is very simple and similar to class definition. We use keyword interface to define an interface.

Example: Here interface named Vehicle is defined

By default all the methods inside interface are public abstract and all the fields are final static. So when we do not initialize the field variable, it will produce compile time errors.

Interface can extend another interface. Actually an interface can extend number of interfaces, that is interfaces support multiple inheritance. We use keyword extends followed by comma separated list of parent interfaces.

Example: An interface inheriting both interfaces Vehicle and LoadCarrier

We can implement the interface using implements keywords. A class implementing particular interface need to implement all the methods in the interface.

Example: A class MyTrucks implements the interface Truck.

Here The class MyTruck must contain definitions of all the seven methods. One from interface Truck and other six methods from parent interfaces of Tuck.

A class can implement multiple interfaces using keyword implements followed by comma separated list of interfaces.

Example: A class MyTrucks implementing multiple interfaces Vehicle and LoadCarrier.

In above example MyTruck class must contain definitions for all the six methods, four methods from interface Vehicle and two methods from LoadCarrier.

If you have to inherit a super class and extend the interface Use Extends first then after implements. If we reverse the order of extends and implements it will produce error.

Example: Here Class MyTruck inherit a class and implement an interface.

Remember This:

  • All the methods in interface are abstract. So if you try to define method body it will produce error.
  • All the fields in interface are static and final by default. So member fields should be initialized within interfaces.
  • Interface members can not be private and protected because these are used in the other classes.
  • Interfaces can not be final.
  • We can not create objects from interface but we can create references. Since constructors should not be there inside interface.
  • We should have to implement all the methods in interface.

Note: Some interfaces are called marker interfaces which do not contain even a single method. Example Serializable, Clonnable and Remote.

Facebook Comments