Jump to content

Interface (Java)

From Alfawiki
Java interface
IndustrySoftware development, Programming languages

An interface within the Java programming language serves as an abstract type designed to specify behaviors that classes are required to implement, functioning similarly to protocols. Defined using the interface keyword, interfaces exclusively include method signatures and constant declarations—variables that are both static and final. Before Java 8, methods in interfaces lacked any implementation. From Java 8 onward, interfaces may contain default and static methods with concrete implementations. Java 9 further expanded this capability by adding private and private static methods. As of March 2025, a Java interface can define up to six distinct categories of methods.

Interfaces cannot be instantiated directly; instead, they must be implemented by classes. When a class implements an interface, it is obligated to provide definitions for all non-default methods or otherwise be declared abstract. Java supports references typed as interfaces, which must either reference an object implementing the interface or be set to null.

One significant commercial benefit of interfaces is their ability to mimic multiple inheritance, which Java restricts for classes—each class may inherit from only one superclass except for , the root class. However, interfaces can extend several other interfaces simultaneously, and classes can implement multiple interfaces.

Overview

Interfaces represent shared capabilities across various classes without enforcing a strict class hierarchy. For example, both a human and a parrot can whistle, yet they do not derive from a common Whistler superclass. Instead, both might inherit from an Animal class while implementing the Whistler interface.

Additionally, interfaces facilitate polymorphism by enabling operations on objects based on their behaviors rather than their concrete classes. For instance, a sorting routine might require objects that implement , ensuring they are sortable regardless of their specific class types.

Example: <syntaxhighlight lang="Java"> interface Bounceable {

   double pi = 3.1415;
   void setBounce();  // All interface methods are implicitly public and abstract; implementations are not permitted here.

} </syntaxhighlight>

Essential characteristics of interfaces include:

  • Contain only method declarations and public constants.
  • Cannot be instantiated directly.
  • Must be implemented by classes.
  • Do not extend classes.
  • May extend multiple other interfaces.

Defining an interface

The syntax for defining an interface resembles that of a Java class definition:

[visibility] interface InterfaceName [extends other interfaces] {
        constant declarations
        abstract method declarations
        static method declarations
}

For example: public interface Interface1 extends Interface2;

All methods declared within an interface are implicitly public and abstract, making the explicit use of the abstract keyword unnecessary. A straightforward example: <syntaxhighlight lang="java"> public interface Predator {

   boolean chasePrey(Prey p);
   void eatPrey(Prey p);

} </syntaxhighlight>

Members of an interface are implicitly static, final, and public but may be of any class or interface type.

Incorporating Interfaces into Classes

To have a class adopt interfaces, use the following syntax:

... implements InterfaceName[, additional interfaces, ...] ...

Illustration: <syntaxhighlight lang="java"> public class Lion implements Predator {

   @Override
   public boolean chasePrey(Prey p) {
          // Lion-specific implementation
   }
   @Override
   public void eatPrey(Prey p) {
          // Lion-specific implementation
   }

} </syntaxhighlight>

When a class does not provide implementations for every method defined in an interface, it must be marked as abstract, thereby delegating the implementation duty to its subclasses. Any subclass that also fails to implement all required methods must likewise be declared abstract.

A single class is capable of implementing several interfaces simultaneously: <syntaxhighlight lang="Java"> public class Frog implements Predator, Prey { ... } </syntaxhighlight>

Interfaces can define methods shared among classes: <syntaxhighlight lang="Java"> class Animal implements LikesFood, LikesWater {

   boolean likes() { return true; }

} </syntaxhighlight>

Nonetheless, a class cannot implement identical or equivalent interfaces more than once: <syntaxhighlight lang="Java"> class Animal implements Shares<Boolean>, Shares<Integer> ... // Compilation error: duplicate interface implementation </syntaxhighlight>

Within Java, interfaces are extensively utilized for callbacks because Java prohibits multiple inheritance of classes and does not allow methods to be passed directly as parameters. To simulate passing a method as an argument, programmers create and pass an interface reference that defines the method signature and points to its implementation, thus circumventing the need for multiple versions of the same method for various caller classes.

Extending Interfaces

Unlike classes, interfaces support multiple inheritance by extending several other interfaces concurrently. For instance: <syntaxhighlight lang="java"> public interface VenomousPredator extends Predator, Venomous {

   // Interface content

} </syntaxhighlight> If both Predator and Venomous declare or inherit methods with identical signatures—such as kill(Prey p)—a class implementing VenomousPredator will be required to implement that method only once, fulfilling both contracts.

Illustrative Examples

Notable Java interfaces include:

  • , which contains the method , designed for object comparison. Generics allow specifying the types that can be compared.
  • , a marker interface without any methods or attributes, indicating that a class can be serialized. Its Javadoc describes the expected behavior but does not enforce it programmatically.

Related Topics

Additional Resources