What is the purpose of the default keyword in Java

2019-01-30 21:38发布

An interface in Java is similar to a class, but the body of an interface can include only abstract methods and final fields (constants).

Recently, I saw a question, which looks like this

interface AnInterface {
    public default void myMethod() {
        System.out.println("D");
    }
}

According to the interface definition, only abstract methods are allowed. Why does it allow me to compile the above code? What is the default keyword?

On the other hand, when I was trying to write below code, then it says modifier default not allowed here

default class MyClass{

}

instead of

class MyClass {

}

Can anyone tell me the purpose of the default keyword? Is it only allowed inside an interface? How does it differ from default (no access modifier)?

7条回答
Viruses.
2楼-- · 2019-01-30 22:43

Something that was overlooked in the other answers was its role in annotations. As far back as Java 1.5, the default keyword came about as a means to provide a default value for an annotation field.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Processor {
    String value() default "AMD";
}

It usage was overloaded with the introduction of Java 8 to allow one to define a default method in interfaces.

Something else that was overlooked: the reason that the declaration default class MyClass {} is invalid is due to the way that classes are declared at all. There's no provision in the language that allows for that keyword to appear there. It does appear for interface method declarations, though.

查看更多
登录 后发表回答