从间接继承的界面中选择默认实现不起作用
我有4个看起来像这样的类:
public interface Foo<T> {
...
default boolean isEmpty() {
return false; //dummy value real implementation is not relevant for the problem
}
}
public interface CharSequence { //java.lang.CharSequence
...
default boolean isEmpty() {
return true; //dummy value real implementation is not relevant for the problem
}
public abstract class Bar<T> implements Foo<T> {
...
}
public final BarImpl extends Bar<Character> implements CharSequence { //typical diamond problem
...
@Override
public boolean isEmpty() { //needed to resolve diamond problem
return Foo.super.isEmpty() // Compile Error: No enclosing instance of the type Foo<T> is accessible in scope
return Bar.super.isEmpty() // Compile Error: No enclosing instance of the type Bar<T> is accessible in scope
return CharSequence.super.isEmpty() // compiles
}
为什么我无法访问扩展栏的默认实现?
I have 4 Classes that look like this:
public interface Foo<T> {
...
default boolean isEmpty() {
return false; //dummy value real implementation is not relevant for the problem
}
}
public interface CharSequence { //java.lang.CharSequence
...
default boolean isEmpty() {
return true; //dummy value real implementation is not relevant for the problem
}
public abstract class Bar<T> implements Foo<T> {
...
}
public final BarImpl extends Bar<Character> implements CharSequence { //typical diamond problem
...
@Override
public boolean isEmpty() { //needed to resolve diamond problem
return Foo.super.isEmpty() // Compile Error: No enclosing instance of the type Foo<T> is accessible in scope
return Bar.super.isEmpty() // Compile Error: No enclosing instance of the type Bar<T> is accessible in scope
return CharSequence.super.isEmpty() // compiles
}
Why can't I access the default implementation coming from extending Bar?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
barimpl
无法调用foo
's默认
明确地方法,因为barimpl
不是直接实现foo <
/代码>。它正在扩展bar
直接实现foo
,因此,它是bar
替代foo
's默认方法方法与否。
barimpl
只能调用bar
'sisempty()
通过super.isempty()
,可能最终会出现foo
's默认
方法如果bar
决定不覆盖它或以bar
的具体方法(如果为请注意,
t.super.method()
才能使用,t
是直接实现的超级接口(即尚未由超级类或其他超级界面实现)或如果t
是内部类的封闭类型。第二个用例是“ no enclosing实例…”的原因,在范围中可以访问”错误消息。BarImpl
can not invokeFoo
’sdefault
method explicitly, asBarImpl
is not directly implementingFoo
. It’s extendingBar
which directly implementsFoo
, hence, it’sBar
’s decision to overrideFoo
’sdefault
method or not.BarImpl
can only invokeBar
’sisEmpty()
method viasuper.isEmpty()
, which may end up atFoo
’sdefault
method ifBar
decides not to override it or at a concrete method ofBar
if it does override it.Note that
T.super.method()
can only be used if either,T
is a directly implemented super interface (i.e. not already implemented by a super class or another super interface) or ifT
is an enclosing type of an inner class. The second use case is the reason for the “No enclosing instance of … is accessible in scope” error message.