- It is a collection of constants and abstract methods.
- It can either contain constants or abstract methods or both.
- It does not have instance variables and all the methods in it are defined without a body.
- To make use of it, the interface should be implemented in a class, implementing the interface and write the code for each of the methods. free to determine the details of its own implementation.
Defining an Interface:
- Defined just like a class but by using the keyword 'interface'.
accessmode interface Name
returntype methodname1(parameter list);
returntype methodname2(parameter list);
type final variablename1=value;
type final variablename2=-value;
type final variablenameN=value;
- Methods are always abstract and public and so need not explicitly specify them.
- Constants are always public, static and final and so need not explicitly specify for these, either.
- Cannot have static methods or static blocks inside it.
- If the interface is declared as public, it can be used by any other code. In that case, the interface must be the only public interface declared in the file and the file must have the same name as the interface.
public interface Shape
public class ShapeMain ---> Wrong, as there can be only a single public class or interface within a file.
Examples for defining an interface:
i) interface Sample
void display(int n);
ii) interface Conversion
double HP_TO-WATT = 745.7;
double WATT_TO_HP = 1/ HP_TO-WATT;
(i) Interface Sample contains a constant and one abstract method.
(ii) Interface Conversion contains only constants. The value of one constant can be defined in terms of a preceding constant. If we try to use a constant that is defined later in the interface, the code will not compile.
KM_TO_M = 1000;
M_TO_KM = 1/ KM_TO_M;
M_TO_KM = 1/ KM_TO_M; ---> Wrong
KM_TO_M = 1000;
Implementing the Interface:
- To implement an interface, including the 'implements' clause in the class definition, and then define the methods declared by the interface.
class className [extends superclass] [implements interface1 [,interface2 ...]] //These 2 orders should not be changed
- If the class extends another class and implements an interface, 'extends' clause should appear first and then the 'implements' clause. This is because a class can extend only one superclass but can implement multiple interfaces separated by a comma.
- The methods that implement an interface must be declared public as all the methods in an interface are public, by default.
Advantages of interfaces:
- Helps in multiple inheritances.
- There are a number of situations in Software Engineering when disparate groups of programmers agree to a contract that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Interfaces are such contracts.