What are the differences between interfaces in Kotlin and Java?
sobes.tech AI
Answer from AI
Main differences:
-
Default method implementation: In Java 8 and above, interfaces can implement methods with bodies (default methods). In Kotlin, interface methods have default bodies. The
defaultkeyword is not required. -
Abstract and open methods: In Java, all interface methods are implicitly abstract. To make a method with a body,
defaultmust be used. In Kotlin, interface methods with bodies are implicitlyopenand can be overridden in implementing classes. Methods without bodies are implicitlyabstract. -
Properties: Java interfaces cannot contain fields, only constants (
final static). Kotlin interfaces can declare abstract properties, which must be implemented in classes, or properties with default getters/setters (backstage fields are not stored). -
Constructors: Java interfaces cannot contain constructors. Kotlin interfaces cannot contain constructors.
-
Visibility modifiers: In Java, interface methods are implicitly
public. In Kotlin, interface methods are implicitlypublic open.
| Feature | Kotlin | Java |
|---|---|---|
| Method implementation | Allowed (by default) | Allowed (with default) |
| Method abstractness | Without body - abstract, with body - open |
Without body - abstract, with body - default |
| Properties | Allowed (abstract or with accessors) | Not allowed (only constants) |
| Constructors | Not allowed | Not allowed |
| Visibility modifier | public open by default |
public by default |
Kotlin example:
interface MyInterface {
val myProperty: String // Abstract property
fun abstractMethod() // Abstract method
fun defaultMethod() {
// Default implementation
println("Default implementation in Kotlin interface")
}
}
Java example:
interface MyInterfaceJava {
// No properties, only constants allowed
// public static final String MY_CONSTANT = "value";
void abstractMethod(); // Abstract method (implicitly public and abstract)
default void defaultMethod() { // Default method
// Default implementation
System.out.println("Default implementation in Java interface");
}
}