- Interfaces
- Interfaces in Java
- Interfaces as APIs
- Interfaces in Java | Explained
- What is Interface
- Why Interface
- How to implement interface in Java
- Example
- Person.java
- InterfaceExamples.java
- How to implement multiple interfaces in Java
- Example
- Person.java
- Employee.java
- InterfaceExamples.java
- Conclusion
- About the author
- Anees Asghar
Interfaces
There are a number of situations in software engineering when it is important for disparate groups of programmers to 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. Generally speaking, interfaces are such contracts.
For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobilestop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.
The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group’s software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.
Interfaces in Java
In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiatedthey can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.
Defining an interface is similar to creating a new class:
public interface OperateCar < // constant declarations, if any // method signatures // An enum with values RIGHT, LEFT int turn(Direction direction, double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); . // more method signatures >
Note that the method signatures have no braces and are terminated with a semicolon.
To use an interface, you write a class that implements the interface. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. For example,
public class OperateBMW760i implements OperateCar < // the OperateCar method signatures, with implementation -- // for example: public int signalTurn(Direction direction, boolean signalOn) < // code to turn BMW's LEFT turn indicator lights on // code to turn BMW's LEFT turn indicator lights off // code to turn BMW's RIGHT turn indicator lights on // code to turn BMW's RIGHT turn indicator lights off >// other members, as needed -- for example, helper classes not // visible to clients of the interface >
In the robotic car example above, it is the automobile manufacturers who will implement the interface. Chevrolet’s implementation will be substantially different from that of Toyota, of course, but both manufacturers will adhere to the same interface. The guidance manufacturers, who are the clients of the interface, will build systems that use GPS data on a car’s location, digital street maps, and traffic data to drive the car. In so doing, the guidance systems will invoke the interface methods: turn, change lanes, brake, accelerate, and so forth.
Interfaces as APIs
The robotic car example shows an interface being used as an industry standard Application Programming Interface (API). APIs are also common in commercial software products. Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product. An example would be a package of digital image processing methods that are sold to companies making end-user graphics programs. The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company’s API is made public (to its customers), its implementation of the API is kept as a closely guarded secretin fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.
Interfaces in Java | Explained
In Java, an interface is nothing but a blueprint of a class and it can have static, constants, and abstract methods. It is very much similar to the class as variables and methods can be created in the interfaces as well. However, the major difference is that an interface can have only constant fields/variables, abstract methods and we can’t create the object of an interface. In java, an abstract class can have one or more abstract methods while in an interface, by default all the methods will be abstract.
This write-up will provide a detailed understanding of the following concepts regarding java interfaces:
What is Interface
An interface is a template of a class that consists of abstract methods and constant fields. The data abstraction can be achieved by means of Java interfaces. The Java interfaces hold only the signature (declaration) of methods and will be defined in the implemented class.
The basic syntax of an interface includes an “interface” keyword followed by the name of the interface:
// constant fields/variable declaration
// abstract methods declaration
The Java interface can be implemented in a class with the help of the “implements” keyword:
class ClassName implements InterfaceName {
//define interface methods here
Why Interface
The below-listed features provide the major reasons to use an interface in Java:
- Abstraction can be achieved using the interface.
- Multiple-Inheritance can be performed by means of interfaces.
- Loose coupling (class independence) can be achieved using the interface.
How to implement interface in Java
The best way to understand a concept is to experiment with it, so let’s consider some examples that elaborate how to implement an interface in java.
Example
In this example, we create an interface named “Person” and a class named “InterfaceExamples”. The “InterfaceExamples” class implements the interface “Person”:
Person.java
interface Person {
int PERSON_AGE = 32 ;
String PERSON_NAME = «JOHN» ;
public void displayInfo ( ) ;
}
The above code snippet creates an interface, and within the body of the interface, two constant fields and a function named “displayInfo()” are declared:
In the above snippet, we followed the constant naming convention (i.e. UpperCase) however, if we didn’t follow the naming convention, by default these fields will be considered as constant fields in an interface.
InterfaceExamples.java
public class InterfaceExamples implements Person {
public void displayInfo ( ) {
System . out . println ( «Person Name : » + PERSON_NAME ) ;
System . out . println ( «Person Age : » + PERSON_AGE ) ;
}
public static void main ( String [ ] args ) {
InterfaceExamples exp = new InterfaceExamples ( ) ;
exp. displayInfo ( ) ;
}
}
The above snippet shows that the InterfaceExamples class implements the Person Interface:
In the InterfaceExamples class we define the displayinfo() method, and afterwards, within the main method we created an object of the class InterfaceExamples and finally calls the displayinfo() method with the help of class object:
The output verifies that the Person interface is successfully implemented in the InterfaceExamples class.
How to implement multiple interfaces in Java
Java doesn’t support the concept of multiple Inheritance to avoid ambiguity which means in Java, a class can not inherit the properties of multiple superclasses. However, a class can implement multiple interfaces as a result, multiple inheritance can be achieved by means of interfaces.
Example
In the below-given snippet, a class will implement the multiple interfaces:
Person.java
interface Person {
int PERSON_AGE = 32 ;
String PERSON_NAME = «JOHN» ;
public void PersonInfo ( ) ;
}
The Person interface declares two constants and a method PersonInfo().
Employee.java
The employee interface declares a method EmployeeInfo() which takes a parameter.
InterfaceExamples.java
public class InterfaceExamples implements Person, Employee {
public void PersonInfo ( ) {
System . out . println ( «Person Name : » + PERSON_NAME ) ;
System . out . println ( «Person Age : » + PERSON_AGE ) ;
}
public void EmployeeInfo ( String name ) {
System . out . println ( «Employee Name : » + name ) ;
}
public static void main ( String [ ] args ) {
InterfaceExamples exp = new InterfaceExamples ( ) ;
exp. PersonInfo ( ) ;
exp. EmployeeInfo ( «Michael» ) ;
}
}
The below-given screenshot provides the complete code along with output:
The output verifies that both Person and Employee interfaces are implemented successfully.
Conclusion
Java interfaces have abstract methods and constant fields. By default, the variables/fields are public, static, and final while the methods/functions are abstract and public. In Java, neither the object of the interface can be created nor the constructor. The methods/functions of the interface will be defined inside the class that is implementing the interface. A class can implement several interfaces and hence can achieve the functionalities of multiple-Inheritance.
This write-up presents a detailed overview of what is an interface, and how to implement the interface in a class in Java.
About the author
Anees Asghar
I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.