YouTip LogoYouTip

Java Interfaces

# Java Interface An interface (English: Interface) is an abstract type in the Java programming language, a collection of abstract methods, and is usually declared with the `interface` keyword. A class inherits the abstract methods of an interface by inheriting the interface. An interface is not a class. The way to write an interface is similar to a class, but they belong to 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. An interface cannot be instantiated, but it can be implemented. A class that implements an interface must implement all methods described in the interface, otherwise it must be declared as an abstract class. Additionally, in Java, an interface type can be used to declare a variable, which can become a null reference or be bound to an object that implements this interface. ### Similarities between Interface and Class: * An interface can have multiple methods. * Interface files are saved in files ending with `.java`, with the filename being the interface name. * The bytecode file of the interface is saved in a file ending with `.class`. * The corresponding bytecode file of the interface must be in a directory structure that matches the package name. ### Differences between Interface and Class: * An interface cannot be used to instantiate objects. * An interface has no constructors. * All methods in an interface must be abstract methods. After Java 8, non-abstract methods modified with the `default` keyword can be used in interfaces. * An interface cannot contain member variables, except for `static` and `final` variables. * An interface is not inherited by a class, but implemented by a class. * An interface supports multiple inheritance. ### Interface Characteristics * Every method in an interface is implicitly abstract. The methods in an interface are implicitly specified as **public abstract** (they can only be `public abstract`; other modifiers will cause an error). * An interface can contain variables, but the variables in an interface are implicitly specified as **public static final** variables (and can only be `public`; using `private` will cause a compilation error). * Methods in an interface cannot be implemented within the interface; they can only be implemented by the class that implements the interface. ### Differences between Abstract Class and Interface * 1. Methods in an abstract class can have a method body (i.e., can implement the specific function 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 be of type **public static final**. * 3. An interface cannot contain static code blocks and static methods (methods modified with `static`), while an abstract class 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**: After JDK 1.8, static methods and method bodies can be present in interfaces. > > > **Note**: After JDK 1.8, interfaces are allowed to contain concrete implementation methods, called "default methods", which are modified with the `default` keyword. For more information, refer to (#). > > > **Note**: After JDK 1.9, it is allowed to define methods as `private`, so that certain reusable code does not expose the method. For more information, refer to (#). * * * ## Interface Declaration The syntax for declaring an interface is as follows: ```java interface InterfaceName { // Declare variables // Abstract methods } The `interface` keyword is used to declare an interface. Here is a simple example of an interface declaration. ## NameOfInterface.java File Code: ```java /* File name : NameOfInterface.java */ import java.lang.*; // Import package public interface NameOfInterface { // Any type final, static fields // Abstract methods } An interface has the following characteristics: * An interface is implicitly abstract. When declaring an interface, the **abstract** keyword is not necessary. * Every method in an interface is also implicitly abstract, and the **abstract** keyword is not required when declaring it. * All methods in an interface are public. ### Example ## Animal.java File Code: ```java /* File name : Animal.java */ interface Animal { public void eat(); public void travel(); } * * * ## Interface Implementation 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 the class declaration, the `implements` keyword comes after the `class` declaration. The syntax for implementing an interface can use this formula: ## Interface Syntax: ```java ... implements InterfaceName[, OtherInterfaceName, OtherInterfaceName..., ...] ... ### Example ## MammalInt.java File Code: ```java /* 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, the following rules must be noted: * When a class implements the methods of an interface, it cannot throw checked exceptions. Checked exceptions can only be thrown in the interface or in an abstract class that inherits the interface. * When overriding a method, the class must maintain the same method name and should maintain 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, some rules must also be noted: * 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. * * * ## Interface Inheritance An interface can inherit another interface, similar to the way classes inherit. Interface inheritance uses the `extends` keyword, and the sub-interface inherits the methods of the parent interface. The following `Sports` interface is inherited by the `Hockey` and `Football` interfaces: ```java // 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 itself declares four methods and inherits two methods from the `Sports` interface. Thus, 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 not allowed, but interfaces allow multiple inheritance. In multiple inheritance of interfaces, the `extends` keyword is used only once, followed by the inherited interfaces. As shown below: ```java public interface Hockey extends Sports, Event The above code snippet is a legal definition of a sub-interface. Unlike classes, interfaces allow multiple inheritance, and `Sports` and `Event` can define or inherit the same methods. * * * ## Marker Interface The most commonly used marker interface is an interface that contains no methods. A marker interface is an interface with no methods or properties. It merely indicates that its class belongs to a specific type, allowing other code to test and permit certain actions. The purpose of a marker interface: Simply put, it is like stamping an object (marking it), giving the object one or more privileges. For example, the `java.util.EventListener` interface inherited by the `MouseListener` interface in the `java.awt.event` package is defined as follows: ```java package java.util; public interface EventListener { } An interface with no 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 is the original purpose of marker interfaces. A class implementing a marker interface does not need to define any interface methods (because the marker interface has no methods at all), but the class becomes an interface type through polymorphism.
← Java PackageJava Encapsulation β†’