Interface in Java
The interface is similar to the class, except it contains only abstract methods. It does not contain methods body.
The interface must be implemented by a class to provide the body (definition) of its methods.
It cannot be instantiated, so its methods can only be accessed by using the class object.
An interface may have variables that are final by default.
To create an interface, use the interface keyword as you did with creating class in the previous lesson.
Syntax
interface <interface-name>{
// variables
// methods
}
For example,
interface Car{
int speed = 0;
void showSpeed(int speed);
}
Sample Code
interface Car{
void showSpeed(int speed);
}
class BMWCar implements Car{
@Override
public void showSpeed(int speed) {
System.out.println("Car Speed: "+speed);
}
}
class FordCar implements Car{
@Override
public void showSpeed(int speed) {
System.out.println("Car Speed: "+speed);
}
}
public class MainClass{
public static void main(String[] args) {
BMWCar car = new BMWCar();
car.showSpeed(120);
FordCar fcar = new FordCar();
fcar.showSpeed(100);
}
}
Create Interface
To create an interface, use interface keyword and any valid name. We can add any number of methods and variables to the interface. To use this interface, it must be implemented by a class.
Let's learn to create an interface.
Create a Bike interface by using the interface keyword. Initially, it is empty, which means it does not contain any method or variable. Hint
interface Bike{
}
After creating the interface, run the code.
This is how, we created interface. Initially it does nothing. It is just declaration.
interface Car{
void showSpeed(int speed);
}
In the next lesson, we will learn to implement this interface in the class.