I have an abstract wrapping class Foo which get functionality defined by providing it with the Interface Reader. All works well when I'm implementing a seperate Reader and provide it. 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.
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"
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
. Inner classes in Java are bound to an instance of the outer rather than the class unless they're static .
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
.
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
. It's a chicken-and-egg problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.