将对非覆盖派生 class 方法的方法引用传递给其基础 class 是否合法且已定义?
Is it legal and defined to pass a method reference to a non-overriding derived class method to its base class?
将对非重写派生 class 方法的方法引用传递给其基础 class 是否合法且已定义?
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())
为什么不正常做呢?
public class Derived extends Base {
@Override
public Int getInt() {
returnsOne();
}
private Int returnsOne() { return 1; }
}
将对非重写派生 class 方法的方法引用传递给其基础 class 是否合法且已定义?
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())
为什么不正常做呢?
public class Derived extends Base {
@Override
public Int getInt() {
returnsOne();
}
private Int returnsOne() { return 1; }
}