[英]Inner class object as Outer class constructor argument
I have an abstract wrapping class Foo which get functionality defined by providing it with the Interface Reader. 我有一个抽象包装类Foo,它通过提供Interface Reader来定义功能。 All works well when I'm implementing a seperate Reader and provide it.
当我实现一个单独的Reader并提供它时,一切正常。 It goes wrong when I'm, trying to do this via a inner class.
当我试图通过内部阶级来做这件事时,它会出错。 Having the Reader implementation in an inner class is a requirement for me.
将Reader实现在内部类中是我的要求。
public abstract class Foo
{
private Reader reader;
public Foo(Reader reader)
{
this.reader = reader;
}
public void read()
{
this.reader.doit();
}
}
"No enclosing instance of type MapLink is available due to some intermediate constructor invocation" “由于某些中间构造函数调用,没有可用的MapLink类型的实例”
public class ReaderFoo extends Foo
{
public class FooReader implements Reader
{
@Override
public void doit()
{
// functionality
}
}
public ReaderFoo ()
{
super(new FooReader());
}
}
What am I doing wrong? 我究竟做错了什么?
Try making FooReader
static
. 尝试使
FooReader
static
。 Inner classes in Java are bound to an instance of the outer rather than the class unless they're static . Java中的内部类绑定到外部实例而不是类,除非它们是静态的 。
public class ReaderFoo extends Foo
{
public static class FooReader implements Reader
{
@Override
public void doit()
{
// functionality
}
}
public ReaderFoo ()
{
super(new FooReader());
}
}
You cannot use an instance inner class before actually having an instance, as the actual type of the Reader
is going to be like myInstance.Reader
. 在实际拥有实例之前,您不能使用实例内部类,因为
Reader
的实际类型将类似于myInstance.Reader
。
The issue is that the constructor to FooReader
requires the outer class ( ReaderFoo
) to be instantiated before it (because inner classes store a reference to their containing instance), but you're making one in the constructor to ReaderFoo
. 问题是
FooReader
的构造FooReader
需要在它之前实例化外部类( ReaderFoo
)(因为内部类存储对其包含实例的引用),但是你在构造函数中为ReaderFoo
创建一个。 It's a chicken-and-egg problem. 这是一个鸡蛋问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.