What is the purpose of the default keyword in Java?

后端 未结 8 791
别那么骄傲
别那么骄傲 2020-12-02 08:28

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

8条回答
  •  天涯浪人
    2020-12-02 08:52

    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.

提交回复
热议问题