Interface in Java
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance in
Java.
The java compiler adds public and abstract keywords before the interface method. More, it
adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public and
abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
interface printable{
void print();
obj.print();
Test it Now
Output:
Hello
File: TestInterface1.java
//Interface declaration: by first user
interface Drawable{
void draw();
class TestInterface1{
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}
Test it Now
Output:
drawing circle
interface Bank{
float rateOfInterest();
class TestInterface2{
System.out.println("ROI: "+b.rateOfInterest());
}}
Test it Now
Output:
ROI: 9.15
void print();
interface Showable{
void show();
obj.print();
obj.show();
}
}
Test it Now
Output:Hello
Welcome
interface Printable{
void print();
interface Showable{
void print();
obj.print();
}
Test it Now
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
A class implements interface but one interface extends another interface .
interface Printable{
void print();
void show();
obj.print();
obj.show();
}
Test it Now
Output:
Hello
Welcome
File: TestInterfaceDefault.java
interface Drawable{
void draw();
class TestInterfaceDefault{
d.draw();
d.msg();
}}
Test it Now
Output:
drawing rectangle
default method
File: TestInterfaceStatic.java
interface Drawable{
void draw();
class TestInterfaceStatic{
d.draw();
System.out.println(Drawable.cube(3));
}}
Test it Now
Output:
drawing rectangle
27
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail
in the nested classes chapter. For example:
interface printable{
void print();
interface MessagePrintable{
void msg();
prev next
Please Share
Latest 4 Tutorials
ADO.NET