Interface in Java
In Java, an interface is a collection of abstract methods and constants (static final variables). It defines a set of methods that a class implementing the interface must provide. An interface is similar to a class, but it cannot be instantiated directly. Instead, other classes can implement an interface, which means that they provide an implementation for all of the methods declared in the interface.
To define an interface in Java, you use the interface
keyword followed by the name of the interface. Here's an example:
javapublic interface Printable {
void print();
}
In this example, the Printable
interface declares a single abstract method called print()
. Any class that implements the Printable
interface must provide an implementation for this method.
To implement an interface in Java, you use the implements
keyword followed by the name of the interface. Here's an example:
javapublic class Printer implements Printable {
public void print() {
// implementation of the print method
}
}
In this example, the Printer
class implements the Printable
interface by providing an implementation for the print()
method.
Interfaces can also extend other interfaces, allowing you to build hierarchies of interfaces. Here's an example:
javapublic interface Colorable {
void setColor(String color);
}
public interface PrintableColorable extends Printable, Colorable {
// no additional methods
}
public class ColorPrinter implements PrintableColorable {
public void print() {
// implementation of the print method
}
public void setColor(String color) {
// implementation of the setColor method
}
}
In this example, the Colorable
interface declares a single method called setColor()
. The PrintableColorable
interface extends both the Printable
and Colorable
interfaces. Finally, the ColorPrinter
class implements the PrintableColorable
interface by providing implementations for both the print()
and setColor()
methods
Comments
Post a Comment