Interfaces in Java
Interfaces in Java
Interfaces specify what a class must do and not how. It is the blueprint of the
class.
An Interface is about capabilities like a Player may be an interface and any
class implementing Player must be able to (or must implement) move(). So it
specifies a set of methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
Syntax :
interface <interface_name> {
interface Player
{
final int id = 10;
int move();
}
// A simple interface
interface In1
{
// public, static and final
final int a = 10;
// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
Output:
Geek
10
A real-world example:
Let’s consider the example of vehicles like bicycle, car, bike………, they have common
functionalities. So we make an interface and put all these common functionalities. And lets
Bicycle, Bike, car ….etc implement all these functionalities in their own class in their own way.
import java.io.*;
interface Vehicle {
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
Output;
Bicycle present state :
speed: 2 gear: 2
Bike present state :
speed: 1 gear: 1