As classes in Java cannot have more than one class.For instance , a definition like
class A extends B extends C
{
............
............
}
is not permitted in Java.
Since multiple inertiance is an important concept in OOP paradigm ,Java provides an alternative approach known as interface to support the concept of multiple inheritance.
An interface in Java is basically a kind of class. Interfaces can have abstract methods and variables. It cannot have a method body. (means that interfaces do not specify any code to implement these methods and data fields contain only constants).
Therefore, it is the responsibility of class to implements an interface to define class that implements an interface to define the code for implementation of these methods.
Why use Java interface?
- By interface, we can achieve the functionality of multiple inheritance.
- It is used to achieve abstraction.
- It can be used to achieve loose coupling.
Syntax for defining an interface ,it is very similar to that for defining a class.
interface InterfaceName
{
variables declaration;
methods declaration;
}
Here, interface is the keyword and InterfaceName is any valid Java variable (just like class name). All variables are declared as constants. Methods declaration will contains only a list of methods without any body statements.
Example
interface Area
{
static final float pi=3.14;
float compute (float x,float y);
void show();
}
Difference between class and Interface
Class | Interface |
The members of class can be constant or variables. | The members of an interface are always declared as constant. i.e. their values are final. |
A class describes the attributes and behaviors of an object. | An interface contains behaviors that a class implements. |
Members of a class can be public, private, protected or default. | All the members of the interface are public by default |