DEV Community

Dinesh G
Dinesh G

Posted on

Interface in Java

Interface in Java

An interface in the Java programming language is defined as an abstract type used to specify the behavior of a class. It is a blueprint of a behavior and contains static constants and abstract methods.

Syntax for Java Interfaces

interface {
    // declare constant fields
    // declare methods that are abstract 
    // by default.   
}
Enter fullscreen mode Exit fullscreen mode

To declare an interface, use the interface keyword.

It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public, and all fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface. To implement the interface, use the implements keyword.

Uses of Interfaces in Java

  • It is used to achieve total abstraction.
  • Since Java does not support multiple inheritances in the case of a class, by using an interface, it can achieve multiple inheritances.
  • Any class can extend only one class but can implement multiple interfaces.
  • It is also used to achieve loose coupling.
  • Interfaces are used to implement abstraction.

When to Use Class and Interface?

Use a Class when:

  • Use a class when you need to represent a real-world entity with attributes (fields) and behaviors (methods).
  • Use a class when you need to create objects that hold state and perform actions
  • Classes are used for defining templates for objects with specific functionality and properties.

Use an Interface when:

  • Use an interface when you need to define a contract for behavior that multiple classes can implement.
  • Interface is ideal for achieving abstraction and multiple inheritance.
  • Implementation: To implement an interface, we use the keyword implements

Top comments (0)