Interface in Java2 min read

What is Interface in Java?

An Interface in Java can be defined as a blueprint for a class. It has both static and abstract constants and functions. In Java, the interface is a means of achieving abstraction. An interface in Java can only have abstract methods i.e. methods with no method body. In Java, it is used to achieve abstraction as well as multiple inheritances. To put it another way, interfaces can have abstract methods and variables. A method body isn’t allowed.

  • A collection of abstract techniques makes up an interface.
  • When a class implements an interface, it inherits the interface’s abstract methods.
  • Methods can be declared and defined in any class.
  • Interfaces are the entire abstraction of a class in Java, allowing us to declare what a class must do rather than how it does it.
  • Interfaces are similar to classes, except they lack the definitions of instance variables and methods.
  • In other words, interfaces are classes that solely contain method declarations (without a body).
  • The term ‘interfaces’ is used to declare interfaces.
  • Although writing an interface and writing a class are comparable, they are two distinct concepts.
  • An object’s properties and actions are described by its class.
  • A class’s behaviors are defined via an interface.
  • Unless the interface’s implementation class is abstract, all of the interface’s methods must be declared in the class.
  • Interfaces are used to support dynamic method resolution at run time. They support polymorphism in Java. (one interface multiple methods).

Syntax for interface declaration

interface Name { return_type method(parameter_list); }


Example of an interface

interface Printable{  
  void print();  
} 

class Print implements Printable{  
  public void print(){
    System.out.println("Hello");
  }  
  public static void main(String[] args){  
    Print obj = new Print();  
    obj.print();  
  }  
} 

Output

Hello

Java Interface in a nutshell

In the following ways, an interface is analogous to a class:

  • An interface can have as many methods as it wants. It is written in a file with the extension.java, with the interface’s name matching the file’s name.
  • A .class file contains the byte-code for an interface.
  • Interfaces are contained in packages, and their byte-code files must be stored in a directory structure that corresponds to the package name.

However, an interface is different from a class in several ways, including:

  • An interface cannot be instantiated.
  • There are no constructors in an interface.
  • In an interface, all of the methods are abstract.
  • Instance fields are not allowed in an interface. The only fields that can be used in an interface must be static or final.
  • A class does not extend an interface; instead, it implements it.
  • An interface can be used to expand other interfaces.

Share:

Leave a Reply