Java Interface
Java Interface
Java Interface
Def:
An Interface is basically a kind of class. Like classes, an interface contains final fields
(constants) and abstract methods.
There is responsibility of the class that implements an interface to define the code
for implementation of these methods
Syntax of an interface:
The interface keyword is used to declare an interface.
interface InterfaceName
{
datatype variablename=value;
//Any number of final, static fields
returntype methodname(list of parameters or no parameters)
//Any number of abstract method declarations
}
Explanations
In the above syntax Interface is a keyword interface name can be user defined name the default
signature of variable is public static final and for method is public abstract. JVM will be added
implicitly public static final before data members and public abstract before method.
Example
public static final datatype variable name=value; ----> for data member
Properties of Interface
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Methods in an interface are implicitly public.
All the data members of interface are implicitly public static final.
Here is an example of an interface definition contains two variables and one methods.
Example 1:
interface Item
{
static final int code = 1001;
static final String name="Fan";
void display();
}
Example 2:
interface Area
{
static final float PI = 3.142f;
float compute(float x, float y);
void show();
}
We can combine several interfaces together into a single interface. Following declarations are
valid.
interface ItemConstant
{
int code=1001;
String name="Fan"
}
interface ItemMethods
{
void dispay();
}
inteface extends ItemMethods, ItemConstant
{
----------------------
----------------------
}
Implementing Interfaces:
An interface is used as "superclass" whose properties are inherited by a class. A class
can implement one or more than one interface by using a keyword implements followed by a
list of interfaces separated by commas.
When a class implements an interface, it must provide an implementation of all
methods declared in interface and all its superinterfaces. Otherwise, the class must be
declared as abstract.
This general form shows that a class can extend another class while implementing interfaces.
interface Area
{
double pi = 3.14;
double calcArea(double x, double y);
}
class InterfaceTest
{
public static void main(String arg[])
{
Rect r = new Rect();
circle c = new circle();
System.out.println("\nArea of Rectangle is : " +r.calcArea(10,20));
System.out.println("\nArea of Circle is : " +c.calcArea(15,15)); }
}
OUTPUT:
C:\Users\staff1\Desktop>javac InterfaceTest.java
C:\Users\staff1\Desktop>java InterfaceTest