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.
Java Interface also represents
IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given
below.
- It is used to achieve abstraction.
- By interface, we can support the
functionality of multiple inheritance.
- It can be used to achieve loose
coupling.
Java 8 Interface Improvement
Since Java 8, interface can have default and static methods which
is discussed late
The java compiler adds public and abstract keywords
before the interface method. More, it adds public, static and final keywords
before data members.
Java Interface Example
In this example, Printable
interface has only one method, its implementation is provided in the A class.
- 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();
- }
- }
Output: Hello
Comments
Post a Comment