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

Interface fields are public, static and final by default, and methods are public and abstract.

Java Interface Example

interface printable{ 
void print(); 
} 
class A implements printable{ 
 public void print(){System.out.println("Hello");} 

public static void main(String args[]){ 
A obj = new A(); 
obj.print(); 
 } 
}

Output

Hello

What is marker or tagged interface ?

An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation

How Serializable interface is written ?

. public interface Serializable{ 

 } 

Nested Interface in Java

An interface can have another interface i.e. known as nested interface.

Example

interface printable{ 
void print(); 
 interface MessagePrintable{ 
 void msg(); 
 } 
 }

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can’t be instantiated\

there are many differences between abstract class and interface that are given below

Abstract classInterface
1. Abstract class can have abstract
and non-abstract methods
Interface can have only
abstract methods
2. Abstract class doesn’t support multiple
inheritance
Interface supports multiple
inheritance.
3. Abstract class can have final, non-final, static
and non-static variables.
Interface can’t have static methods,
main method or constructor.
4. Abstract class can have static methods, main method and constructorInterface can’t have static methods,main method or constructor.
5.Abstract class can provide the implementation of interfaceInterface can’t provide the
implementation of abstract class.
6.The abstract keyword is used to declare abstract class.The interface keyword is used to
declare interface.
7. Example :
public abstract class Shape{
public abstract void draw();
}
Example
public interface Drawable{
void draw();
}

Leave a Comment