Advertisement
Google Ad Slot: content-top
Java Interfaces
An interface in Java is a blueprint of a class that contains abstract methods (methods without a body). Interfaces are used to achieve abstraction and multiple inheritance in Java. It defines a set of methods that a class must implement but does not provide the implementation.
Key Points About Interfaces:
- An interface can contain:
- Abstract methods (methods without a body).
- Default methods (methods with a body, introduced in Java 8).
- Static methods (introduced in Java 8).
- Private methods (introduced in Java 9)
- A class can implement multiple interfaces (unlike extending classes, which is limited to one).
- Interfaces cannot have instance variables; they can have constants (public, static, and final by default).
- All methods in an interface are implicitly public and abstract (except default, static, and private methods).
Syntax:
interface InterfaceName {
// Abstract method
void method1();
// Default method (introduced in Java 8)
default void method2() {
System.out.println("Default Method");
}
// Static method (introduced in Java 8)
static void method3() {
System.out.println("Static Method");
}
}