An interface in Java is a type that declares one or more empty methods enforcing the implementing class to provide the body of those methods. All of its methods must be declared without providing any implementation.
package com.techstackjournal.game;
public interface Clickable {
public void onLeftClick();
public void onRightClick();
public void onDoubleClick();
}
Interfaces on their own do not have any great significance, they need to be implemented by a class.
Classes define state and behavior, whereas interfaces can assign additional abilities to a class.
For example, a game consists of many objects, car, book, tree, bicycle etc., You may design your application in such a way that car, book and bicycle to be clickable, but not tree. You want different behaviors when you right click, left click and double click. In this case, you can create an interface called as Clickable with all the required behaviors such as left click, right click and double click in it. This Clickable interface on its own doesn’t make any sense, it has to be assigned to a class.
An interface can be applied to related and unrelated classes. In the above use case, Car and Book are Clickable, but both are unrelated classes. Each of these classes can provide their own implementation of interface methods.
A class can implement an interface using implements keyword in the declaration of the class followed by the name of the Interface. Also, that class has to provide implementation by overriding all the methods of the interface.
package com.techstackjournal.game;
public class Book implements Clickable {
public void onLeftClick() {
// Code
}
public void onRightClick() {
// Code
}
public void onDoubleClick() {
// Code
}
}
If a class doesn’t implement all of the methods of an interface, it has to be declared as an abstract class.
Implementing Multiple Interfaces
Though a class can extend only 1 class, it can implement more than 1 interface. All the interface names must be comma separated after implements keyword.
An Object can have more than one ability so it makes sense to be able to implement more than 1 interface. For example, in our example, Car and Bicycle objects are both Clickable and Controllable.
package com.techstackjournal.game;
public class Car implements Clickable, Controllable {
public void onLeftClick() {
// Code to implement Clickable
}
public void onRightClick() {
// Code to implement Clickable
}
public void onDoubleClick() {
// Code to implement Clickable
}
public void stop() {
// Code to implement Controllable
}
public void start() {
// Code to implement Controllable
}
public void turnLeft() {
// Code to implement Controllable
}
public void turnRight() {
// Code to implement Controllable
}
public void turnBack() {
// Code to implement Controllable
}
}