Java Interface
Java Interface
Syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
A class can extend another class, and similarly, an interface can extend
another interface. However, only a class can implement an interface, and
the reverse (an interface implementing a class) is not allowed.
Example of Interface
import java.io.*;
interface Vehicle {
// Abstract methods defined
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
class Main
{
public static void main (String[] args)
{
// Instance of Bicycle(Object)
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
// Sub interface
interface Sub{
int sub(int a,int b);
}
class GFG{
// Main Method
public static void main (String[] args)
{
// instance of Cal class
Cal x = new Cal();
}
}
Extending Interfaces
One interface can inherit another by the use of keyword extends. When a class
implements an interface that inherits another interface, it must provide an
implementation for all methods required by the interface inheritance chain.
Example
interface A {
void method1();
void method2();
}
Advantages of Interfaces
Without bothering about the implementation part, we can achieve the
security of the implementation.
In Java, multiple inheritances are not allowed, however, you can use
an interface to make use of it as you can implement more than one
interface.