Java Interface

An interface (English: Interface) in the Java programming language is an abstract type, a collection of abstract methods. Interfaces are usually declared with the `interface` keyword. A class inherits the abstract methods of an interface by implementing the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are different concepts. A class describes the properties and methods of an object. An interface contains methods that a class must implement.

Unless the class implementing the interface is an abstract class, the class must define all methods in the interface.

Interfaces cannot be instantiated, but they can be implemented. A class that implements an interface must implement all the methods described in the interface, otherwise it must be declared as an abstract class. In addition, in Java, interface types can be used to declare variables. They can be a null pointer or be bound to an object that implements this interface.

Similarities between interfaces and classes:

  • An interface can have multiple methods.
  • Interface files are saved in files ending with .java, and the file name uses the interface name.
  • The bytecode file of an interface is saved in a file ending with .class.
  • The corresponding bytecode file of an interface must be in a directory structure that matches the package name.

Differences between interfaces and classes:

  • Interfaces cannot be used to instantiate objects.
  • Interfaces have no constructors.
  • All methods in an interface must be abstract methods. After Java 8, interfaces can have non-abstract methods modified with the `default` keyword.
  • Interfaces cannot contain member variables, except for `static` and `final` variables.
  • Interfaces are not inherited by classes, but implemented by classes.
  • Interfaces support multiple inheritance.

Interface features

  • Every method in an interface is also implicitly abstract. Methods in an interface are implicitly specified aspublic abstract(Only `public abstract`; any other modifier will cause an error.)
  • Interfaces can contain variables, but variables in an interface are implicitly specified aspublic static finalvariables (and only `public`; using `private` will cause a compilation error).
  • Methods in an interface cannot be implemented in the interface; they can only be implemented by the class that implements the interface.

Difference between abstract classes and interfaces

  • 1. Methods in an abstract class can have a method body, that is, they can implement the specific functionality of the method, but methods in an interface cannot.
  • 2. Member variables in an abstract class can be of various types, while member variables in an interface can only bepublic static finaltype.
  • 3. Interfaces cannot contain static code blocks and static methods (methods modified with `static`), but abstract classes can have static code blocks and static methods.
  • 4. A class can only inherit one abstract class, but a class can implement multiple interfaces.

Note: Since JDK 1.8, interfaces can have static methods and method bodies.

Note: Since JDK 1.8, interfaces are allowed to contain methods with concrete implementations, called "default methods". Default methods are modified with the `default` keyword. For more information, seeJava 8 Default Methods。

Note: Since JDK 1.9, methods are allowed to be defined as private, so that some reusable code does not expose methods. For more information, seeJava 9 Private Interface Methods。


Declaration of interfaces

The syntax for declaring an interface is as follows:

[visibility] interfaceinterface name[extendsother interface names] { //declare variables //abstract methods }

The `interface` keyword is used to declare an interface. Below is a simple example of an interface declaration.

NameOfInterface.java file code:

/*File name: NameOfInterface.java*/ import java.lang.*; //Import packages public interface NameOfInterface { //Any type final, static fields //Abstract methods }
Interfaces have the following characteristics:
  • Interfaces are implicitly abstract. When declaring an interface, there is no need to useabstractthe keyword.
  • Every method in an interface is also implicitly abstract. When declaring, you also don't needabstractthe keyword.
  • Methods in an interface are all public.

Example

Animal.java file code:

/*File name: Animal.java*/ interface Animal { public void eat(); public void travel(); }

Implementation of interfaces

When a class implements an interface, the class must implement all methods in the interface. Otherwise, the class must be declared as an abstract class.

A class uses the `implements` keyword to implement an interface. In a class declaration, the `implements` keyword is placed after the `class` declaration.

The syntax for implementing an interface can use this formula:

Interface syntax:

...implementsinterface name[, other interface names, other interface names..., ...] ...

Example

MammalInt.java file code:

/*File name: MammalInt.java*/ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } }

The compilation and running result of the above example is as follows:

Mammal eats
Mammal travels

When overriding methods declared in an interface, you need to pay attention to the following rules:

  • When a class implements an interface method, it cannot throw a mandatory exception; the mandatory exception can only be thrown in the interface, or in the abstract class that inherits the interface.
  • When overriding a method, the class must keep the same method name and should keep the same or compatible return type.
  • If the class implementing the interface is an abstract class, then there is no need to implement the methods of the interface.

When implementing an interface, you also need to pay attention to some rules:

  • A class can implement multiple interfaces at the same time.
  • A class can only inherit one class, but can implement multiple interfaces.
  • An interface can inherit another interface, which is similar to inheritance between classes.

Inheritance of interfaces

An interface can inherit another interface, which is similar to inheritance between classes. Interface inheritance uses the `extends` keyword, and a sub-interface inherits the methods of the parent interface.

The following Sports interface is inherited by the Hockey and Football interfaces:

//File name: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } //File name: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } //File name: Hockey.java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); }

The Hockey interface declares four methods by itself and inherits two methods from the Sports interface. In this way, a class implementing the Hockey interface needs to implement six methods.

Similarly, a class implementing the Football interface needs to implement five methods, two of which come from the Sports interface.


Multiple inheritance of interfaces

In Java, multiple inheritance of classes is illegal, but interfaces allow multiple inheritance.

In multiple inheritance of interfaces, the `extends` keyword only needs to be used once, followed by the inherited interfaces. As shown below:

public interface Hockey extends Sports, Event

The above program fragment is a legally defined sub-interface. Unlike classes, interfaces allow multiple inheritance, and Sports and Event can define or inherit the same methods.


Marker interfaces

The most commonly used marker interface is an interface that does not contain any methods.

A marker interface is an interface without any methods or properties. It merely indicates that its class belongs to a specific type, for other code to test and allow certain things to be done.

Purpose of a marker interface: simply and vividly speaking, it is to put a label (stamp) on an object, giving the object certain privileges.

For example: the java.util.EventListener interface, which is inherited by the MouseListener interface in the java.awt.event package, is defined as follows:

package java.util; public interface EventListener {}

An interface without any methods is called a marker interface. Marker interfaces are mainly used for the following two purposes:

  • Establish a common parent interface:

    Just like the EventListener interface, which is a Java API extended by dozens of other interfaces, you can use a marker interface to establish a parent interface for a group of interfaces. For example: when an interface inherits the EventListener interface, the Java Virtual Machine (JVM) knows that this interface will be used in an event delegation scheme.

  • Add a data type to a class:

    This situation is the original purpose of marker interfaces. A class implementing a marker interface does not need to define any interface methods (because a marker interface simply has no methods), but the class becomes an interface type through polymorphism.

Other extensions