Java Interface
An interface (English: Interface) in the Java programming language is an abstract type that is a collection of abstract methods, typically declared using the interface
keyword. A class inherits these abstract methods by implementing the interface.
An interface is not a class; it is similar in structure to a class but represents a different concept. Classes describe object attributes and methods, while interfaces contain methods that classes must implement.
Unless the class implementing the interface is abstract, it must define all the methods declared in the interface.
Interfaces cannot be instantiated but can be implemented. A class that implements an interface must implement all the methods described within the interface, or it must declare itself as abstract. Additionally, in Java, interface types can be used to declare variables, which can be null pointers or bound to objects that implement this interface.
Similarities between Interfaces and Classes:
- An interface can have multiple methods.
- Interface files are saved with a
.java
extension, using the interface's name. - The bytecode files for interfaces are saved with a
.class
extension. - The corresponding bytecode files must be in a directory structure that matches the package name.
Differences between Interfaces and Classes:
- Interfaces cannot be used to instantiate objects.
- Interfaces do not have constructors.
- All methods in an interface must be abstract; however, starting from Java 8, interfaces can include non-abstract methods using the
default
keyword. - Interfaces cannot contain member variables, except for
static
andfinal
variables. - Interfaces are not inherited by classes but are implemented by them.
- Interfaces support multiple inheritance.
Interface Characteristics:
- Each method in an interface is implicitly abstract and is specified as
public abstract
(only these modifiers are allowed; others will result in an error). - Interfaces can contain variables, which are implicitly specified as
public static final
(private modifiers will result in a compilation error). - Methods in an interface cannot be implemented within the interface itself; they must be implemented by the class that implements the interface.
Differences between Abstract Classes and Interfaces:
- Abstract classes can have method bodies, allowing for the implementation of methods, which is not possible in interfaces.
- Member variables in abstract classes can be of any type, whereas those in interfaces must be
public static final
. - Interfaces cannot contain static code blocks or static methods, whereas abstract classes can.
- A class can inherit only one abstract class, but it can implement multiple interfaces.
Note: Starting from JDK 1.8, interfaces can include static methods with method bodies.
Note: Starting from JDK 1.8, interfaces can include methods with concrete implementations called "default methods," which are modified using the default
keyword. For more information, refer to Java 8 Default Methods.
Note: Starting from JDK 1.9, methods can be defined as private
, allowing for code reuse without exposing the methods. For more information, refer to Java 9 Private Interface Methods.
Interface Declaration
The syntax for declaring an interface is as follows:
[Visibility] interface InterfaceName [extends OtherInterfaceNames] {
// Variable declarations
// Abstract method declarations
}
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 package
public interface NameOfInterface {
// Any type of final, static fields
// Abstract methods
}
- Interfaces are implicitly abstract; the
abstract
keyword is not required when declaring an interface. - Each method in an interface is implicitly abstract; the
abstract
keyword is not needed when declaring methods. - All methods in an interface are public.
Example
Animal.java File Code:
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing an Interface
When a class implements an interface, it must implement all the methods in the interface. Otherwise, the class must be declared as abstract.
The implements
keyword is used to implement an interface. It is placed after the class declaration.
The syntax for implementing an interface can be represented as:
Interface Syntax:
...implements InterfaceName[, OtherInterfaceNames, ...] ...
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 above example compiles and runs with the following output:
Mammal eats
Mammal travels
When overriding methods declared in interfaces, there are several rules to be followed:
Classes that implement an interface must not throw checked exceptions that are new or broader than those declared by the interface methods.
The overriding method must have the same name and be consistent with the return type, either the same or a subtype.
If the implementing class is abstract, it does not have to implement the interface methods.
When implementing interfaces, keep in mind the following rules:
A class can implement multiple interfaces.
A class can only extend one class but can implement multiple interfaces.
An interface can extend another interface, similar to class inheritance.
Interface Inheritance
An interface can extend another interface, similar to how classes inherit from each other. Interface inheritance uses the extends
keyword, and the child interface inherits the methods from 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 additional methods and inherits two from the Sports
interface, requiring classes that implement Hockey
to implement six methods.
Similarly, classes that implement the Football
interface need to implement five methods, two of which are inherited from the Sports
interface.
Multiple Interface Inheritance
In Java, multiple inheritance of classes is not allowed, but interfaces can inherit from multiple interfaces.
The extends
keyword is used only once when multiple interfaces are inherited, followed by the inherited interfaces. For example:
public interface Hockey extends Sports, Event
The above snippet is a valid definition of a sub-interface, allowing multiple inheritance where Sports
and Event
can define or inherit the same methods.
Marker Interface
The most common type of inherited interface is one that contains no methods.
A marker interface is an interface with no methods or fields. It simply indicates that a class belongs to a certain type, allowing other code to perform specific actions.
Marker interface purposes: To simply mark an object with a specific privilege.
For example, the MouseListener
interface in the java.awt.event
package inherits from the java.util.EventListener
interface, defined as follows:
package java.util;
public interface EventListener {}
An interface with no methods is known as a marker interface. Marker interfaces are used for the following purposes:
- Establishing a common parent interface:
Like the EventListener
interface in the Java API, which is extended by dozens of other interfaces, a marker interface can establish a group of interfaces as parents. For example, when an interface inherits from the EventListener
interface, the Java Virtual Machine (JVM) knows that the interface is intended for an event delegation scheme.
Adding a data type to a class:
This scenario is the original purpose of a marker interface. A class implementing a marker interface does not need to define any interface methods (since a marker interface has no methods), but the class becomes an interface type through polymorphism.