Interfaces in Java
6 min readSep 17, 2023
In Java, an interface is a type that defines a contract of methods that a class implementing the interface must provide. Here are some key points about interfaces in Java:
- Declaration: You declare an interface using the
interface
keyword, followed by the interface name and a list of method signatures. For example:
public interface MyInterface {
void method1();
int method2(String str);
}
- Methods: In an interface, methods are declared without a body. Classes that implement the interface must provide the actual method implementations.
- Implementing Interfaces: To implement an interface, a class uses the
implements
keyword. For example:
public class MyClass implements MyInterface {
// Implement the methods defined in MyInterface
@Override
public void method1() {
// Method implementation
}
@Override
public int method2(String str) {
// Method implementation
return str.length();
}
}
- Multiple Interfaces: A class can implement multiple interfaces, allowing it to inherit method contracts from each interface.
- Default Methods (Java 8+): Starting from Java 8, interfaces can have default methods with method bodies. These methods provide a default implementation that can be overridden by implementing classes if…