An interface in Java is a reference type that defines a set of method signatures that implementing classes must provide implementations for. It serves as a contract between classes, ensuring that they adhere to a specific set of behaviors. Interfaces provide a way to achieve abstraction and enable code reuse.
To declare an interface, use the interface keyword followed by the interface name. Here's the syntax for declaring an interface in Java:
interface InterfaceName { // Method declarations returnType methodName(parameterList); // Constant variables dataType CONSTANT_NAME = value; // Default method default returnType methodName(parameterList) { // Method implementation } // Static method static returnType methodName(parameterList) { // Method implementation } }
Regular interfaces are the most common type of interfaces in Java. They contain abstract method declarations that must be implemented by classes that implement the interface.
interface RegularInterface { // Abstract method declarations returnType methodName(parameterList); }
Let's consider an example where we have a regular interface called Drawable with a single abstract method draw().
interface Drawable { void draw(); } class Circle implements Drawable { public void draw() { System.out.println("Drawing a circle."); } } class Rectangle implements Drawable { public void draw() { System.out.println("Drawing a rectangle."); } } public class Main { public static void main(String[] args) { Drawable circle = new Circle(); Drawable rectangle = new Rectangle(); circle.draw(); rectangle.draw(); } }
@FunctionalInterface interface FunctionalInterfaceName { // Abstract method declaration returnType methodName(parameterList); }
Let's consider an example where we have a functional interface called Calculator with a single abstract method calculate().
@FunctionalInterface interface Calculator { int calculate(int a, int b); } public class Main { public static void main(String[] args) { Calculator addition = (a, b) -> a + b; Calculator subtraction = (a, b) -> a - b; int result1 = addition.calculate(5, 3); int result2 = subtraction.calculate(8, 4); System.out.println("Result of addition: " + result1); System.out.println("Result of subtraction: " + result2); } }
Marker interfaces, also known as tag interfaces, are interfaces with no methods or constants. They serve as markers to indicate a certain capability or property associated with the implementing class. Examples of marker interfaces in Java include Serializable and Cloneable.
Interfaces are a crucial part of Java programming, enabling code abstraction, modularity, and adherence to contracts. Regular interfaces define a set of abstract methods, functional interfaces provide a single abstract method for functional programming, and marker interfaces serve as markers for specific capabilities. By understanding the types, syntax, and usage of interfaces, you can enhance the flexibility and extensibility of your Java programs.