Definition of an Interface
In Java, an interface is a reference type that defines a contract that classes can implement. It consists of abstract methods (which must be implemented by the implementing class) and static or default methods (which can have a body). Interfaces are used to achieve abstraction and multiple inheritance in Java.
Default Modifiers in an Interface
1. Fields in an Interface
- All fields in an interface are implicitly
public
,static
, andfinal
. - Example:
interface MyInterface {
int VALUE = 10; // This is implicitly public, static, and final
}
Equivalent to:
interface MyInterface {
public static final int VALUE = 10;
}
2. Methods in an Interface
- By default, all methods in an interface are implicitly
public
andabstract
(unless they arestatic
ordefault
). - Example:
interface MyInterface {
void doSomething(); // This is implicitly public and abstract
}
Equivalent to:
interface MyInterface {
public abstract void doSomething();
}
3. default
and static
Methods
- Since Java 8, interfaces can have methods with bodies:
default
methods: Provide a default implementation for methods in the interface.static
methods: Can be called directly from the interface without an instance.
interface MyInterface {
default void defaultMethod() {
System.out.println("This is a default method.");
}
static void staticMethod() {
System.out.println("This is a static method.");
}
}
Summary
Feature | Default Modifier(s) |
---|---|
Fields | public static final |
Methods | public abstract (unless default or static ) |