Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

java - Can @FunctionalInterfaces have default methods?

Why can't I create a @FunctionalInterface with a default method implementation?

@FunctionalInterface
public interface MyInterface {
    default boolean authorize(String value) {
        return true;
    }
}
question from:https://stackoverflow.com/questions/30165060/can-functionalinterfaces-have-default-methods

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can have default methods in a functional interface but its contract requires you to provide one single abstract method (or SAM). Since a default method have an implementation, it's not abstract.

Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract.

and

If a type is annotated with this annotation type, compilers are required to generate an error message unless:

The type is an interface type and not an annotation type, enum, or class.

The annotated type satisfies the requirements of a functional interface.

Here you don't satisfy the functional interface's requirement, so you need to provide one abstract method. For example:

@FunctionalInterface
interface MyInterface {

    boolean authorize(int val);
    
    default boolean authorize(String value) {
        return true;
    }
}

Note that if you declare an abstract method overriding one of a public method from the Object's class it doesn't count, because any implementation of this interface will have an implementation of those methods through at least the Object's class. For example:

@FunctionalInterface
interface MyInterface {

    default boolean authorize(String value) {
        return true;
    }

    boolean equals(Object o);
}

does not compile.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...