Question:
What is the difference between a метод по умолчанию
declared in an interface with the default
modifier and a regular method declared in a regular class?
( update ) Reading
A default method is a method that is declared in an interface with the
default
modifier; its body is always represented by a block. It provides a default implementation for any class that implements an interface without a method override. Default methods are different from concrete methods that are declared in classes.
Answer:
The default method cannot access the object's state (object fields) since there is no object, but it can call other methods and access static data (constants).
The default method avoids having to change all classes that implement this interface.
In a class that implements an interface with default methods, you can override them.
interface I1 {
// это public static final int i = 0;
// но в описании интерфейса public static final можно опустить
int i = 0;
default void m1() {
System.out.println("I1 m1 i = " + i);
m2();
}
void m2();
}
Without default
, this class would not compile:
public class C1 implements I1 {
@Override
public void m2() {
System.out.println("C1 m2");
}
public static void main(String[] args) {
new C1().m1();
new C1().m2();
}
}
The output will be:
I1 m1 i = 0
C1 m2
C1 m2