Interface in Java 1.1 Interface in Java?: How To Declare An Interface?
Interface in Java 1.1 Interface in Java?: How To Declare An Interface?
Interface in Java 1.1 Interface in Java?: How To Declare An Interface?
2. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
There are mainly three reasons to use interface. They are given below.
Syntax :
Interface <interface_name>
{
}
Note : The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.In other words,
Interface fields are public, static and final by default, and the methods are public and abstract.
{ {
} }
EXAMPLE
interface printable{
void print(); }
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
Obj.print();
}
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by someone
else. The implementation part is hidden by the user who uses the interface.
File: TestInterface1.java
//Interface declaration: by first user
} {
class Rectangle implements Drawable{ d.draw();
public void draw(){System.out.println("drawing rectangle");} }
} }
}
} {
public float rateOfInterest(){return 9.15f;} {
class PNB implements Bank{ System.out.println(“ROI”+rateOfInterest()));
public float rateOfInterest(){return 9.7f;} }}
} output:
ROI: 9.15
# Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
INTERFACE INTERFACE
in INTERFACE INTERFACE
1. interface Printable{ Hello
2. void print(); Welcome
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable, Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }