An internal class object as an argument to an Outer class constructor

I have an abstract packaging class Foo that gets the functionality defined by the provision of its Reader interface. Everything works well when I implement a separate Reader and provide it. This happens incorrectly when I try to do this through an inner class. Implementing Reader in the inner class is a must for me.

public abstract class Foo { private Reader reader; public Foo(Reader reader) { this.reader = reader; } public void read() { this.reader.doit(); } } 

"There is no instance of an instance of MapLink type available due to some invocation of the intermediate constructor"

 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?

+4
source share
2 answers

Try making FooReader static . Inner classes in Java are associated with an instance of an external, not a class, if they are not 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 the inner class of an instance before you have an instance, since the actual type of Reader will be similar to myInstance.Reader .

+4
source

The problem is that the FooReader constructor requires an external class ( ReaderFoo ) to be created in front of it (since the inner classes store a reference to their containing instance), but you do it in the ReaderFoo constructor. This is a problem with chicken and egg.

+3
source

Source: https://habr.com/ru/post/1483758/


All Articles