有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

oop为什么我们不能在函数接口中重载抽象方法?(爪哇)

所以我熟悉java中的函数接口,以及它们在lambda表达式中的使用。一个函数接口只能包含一个抽象方法。当从lambda表达式中使用这个单独的方法时,您不需要指定它的名称——因为接口中只有一个抽象方法,编译器知道这就是您引用的方法

示例:

// Functional Interface:

@FunctionalInterface
public interface Ball
{
    void hit();
}

// Lambda to define, then run the hit method:

Ball b = () -> System.out.println("You hit it!");

b.hit();

虽然很明显为什么一个函数接口只能包含一个抽象方法,但我不明白为什么不可能重载该方法

例如,以下内容将不会编译:

// (NOT) Functional Interface:

@FunctionalInterface
public interface Ball
{
    void hit();
    void hit(boolean miss);
}

// Lambda to define, then run the hit method:

Ball b = () -> System.out.println("You hit it!");
Ball ba = (boolean miss) -> System.out.println(miss);

b.hit();
ba.hit(false);

编译器声明Ball接口不起作用,因为它包含多个方法,但在这种情况下,我不理解为什么这会是一个问题——只要这两个方法采用不同的参数,就可以根据我定义的参数推断我在lambda中引用的方法

有人能解释为什么不能在函数接口中重载抽象方法吗


共 (0) 个答案