Java Interfaces

‮:sptth‬//www.theitroad.com

In Java, an interface is a collection of method signatures that a class can implement. An interface defines a set of methods that a class must implement if it implements that interface. An interface defines only the method signatures, but not their implementation. In other words, an interface provides a contract between the class and the user of that class, specifying the methods that the class must provide and how those methods can be used.

An interface is declared using the "interface" keyword in Java. Here is an example of an interface in Java:

public interface Printable {
    void print();
}

In this example, the Printable interface defines a single method called "print()", which has no implementation. A class that implements the Printable interface must provide an implementation for the "print()" method.

To implement an interface in a class, the "implements" keyword is used. Here is an example of a class that implements the Printable interface:

public class Document implements Printable {
    public void print() {
        System.out.println("Printing document...");
    }
}

In this example, the Document class implements the Printable interface and provides an implementation for the "print()" method. By implementing the Printable interface, the Document class must provide an implementation for the "print()" method, and can be used wherever a Printable object is expected.

Multiple interfaces can be implemented by a single class using a comma-separated list of interface names in the class declaration. Here is an example of a class that implements multiple interfaces:

public class MyClass implements Interface1, Interface2, Interface3 {
    // class body
}

In this example, the MyClass class implements three different interfaces: Interface1, Interface2, and Interface3. The class must provide an implementation for all the methods declared in these interfaces.

Interfaces can be used to define a common set of behaviors or properties that can be shared by multiple classes. This can help to reduce code duplication and improve the overall structure and organization of a program. Interfaces are widely used in Java programming to define contracts between classes and to provide a standard way of interacting with objects.