首页 > 解决方案 > 将非覆盖派生类方法的方法引用传递给其基类是否合法且已定义?

问题描述

将非覆盖派生类方法的方法引用传递给其基类是否合法且已定义?

public class Base {
   private Supplier<Int> intSupplier;

   public Base(Supplier<Int> intSupplier) { 
        this.intSupplier = intSupplier;
   }

   public Int getInt() { 
        return inSupplier.get(); 
   }
}

.

public class Derived extends Base {
   public Derived() {
      super(this::returnsOne);
   }

   private Int returnsOne() { return 1; }
}

.

assert(1 == new Derived().getInt())

标签: javainheritancemethod-reference

解决方案


为什么不正常做?

public class Derived extends Base {

   @Override
   public Int getInt() { 
        returnsOne(); 
   }

   private Int returnsOne() { return 1; }
}

推荐阅读