There are multiple ways we can use the interface. Those are explained in this topic. This topic also explains about Marker Interfaces.
Shown below are few examples on the usage of interface.
- A simple interface. When class
A
implements IA
, then it has to implement all the methods in the interface IA
.
interface IA
{
void method1();
int method2(int x, int y);
}
class A implements IA
{
public void method1()
{
// Some code here
}
public int method2(int x, int y)
{
// Some code here
}
}
- An interface extending other interface. Here interface
IB
extends interface IA
and when B
implements interface IB
, it has to implement the methods from interface IA
as well as interface IB
.
interface IA
{
void method1();
int method2(int x, int y);
}
interface IB extends IA
{
double method3();
}
class B implements IB
{
public void method1()
{
// Some code here
}
public int method2(int x, int y)
{
// Some code here
}
public double method3()
{
// Some code here
}
}
- An interface extending multiple interfaces. Here interface
ID
extends from IA
, IB
and IC
. If we define any class implementing ID
, then the methods methodA
, methodB
, methodC
and methodD
has to be implemented.
interface IA
{
void methodA();
}
interface IB
{
void methodB();
}
interface IC
{
void methodC();
}
interface ID extends IA, IB, IC
{
void methodD();
}
- Its not necessary for an interface to have at least one method, i.e. An interface can exist with out any methods. An interface with out any methods is called Marker Interface. Interface
IA
defined below is one such Marker Interface, since it does not have any methods. A famous marker interface in Java is Serializable
.
- Also note that interface
IC
which extends from IA
and IB
does not add any more methods. IC
is not considered Marker interface since it inherits methodB
from interface IB
.
interface IA
{
}
interface IB
{
void methodB();
}
interface IC extends IA, IB
{
}
- An interface can have constant (
public static final
) variables. In fact, it can have only public static final
variables. Either we put these modifiers before or not, they will be considered as public static final
. For e.g., PI
, PI_2
and PI_3
are such variables. Even though we do not put the modifiers public static final
before, they will behave as if they are public static final
.
interface IA
{
public static final double PI = 3.14;
double PI_2 = 3.14;
static double PI_3 = 3.14;
void method1();
}