0

How to initialize a class inheriting from an inner class? Why foo1.this() won't compile?

class Foo1 { class Inner { } } class Foo2 extends Foo1.Inner { //Foo2(Foo1 foo1) {foo1.this();} //won't compile Foo2(Foo1 foo1) {foo1.super();} } 
2
  • 5
    This seems really smelly. Foo1.Inner should probably just be a top-level class. Commented May 14, 2012 at 13:42
  • I don't think you can do this in an outside class. Commented May 14, 2012 at 13:45

3 Answers 3

2

If you declare the Inner class static you can do it else you need an instance of the outer class Foo1.

class Foo1 { static class Inner { } } 

But your direct questions seems strange:

foo1.this(); //won't compile 

What are you trying to do here? Call a method called "this" it looks like, but hoping to use the no-argument constructor perhaps? Just use this() if so.

Sign up to request clarification or add additional context in comments.

2 Comments

When you have an inner class, not nested (static), that class is living in the scope of the outer (two instances of the outer class have two different inner classes, even though the look/named the same). So you have a constructor with the outer class instance as the parameter. That is how you can "reach" (qualify) to reach the parent inner class constructor. Just writing superwon't work as there is a level of indirection as you are sub classing.
You could create the parent instance in the subclass as well instead of having it as a constructor parameter, but then it sounds like you could just use a nested (static) class instead. new Foo1().super();
1

I'm not sure I understand what foo1.this(); is supposed to do. Perhaps you are trying to call the default constructor of Inner. Since Inner is a not a static class, it does not have a no argument constructor. It only looks that way. In reality, it has a constructor which takes a Foo1 argument containing the reference to its parent object.

The call to foo1.super(), however, will work just fine. It will call the constructor of the new Inner instance with foo1 as implicit parent reference. That is, the new Inner instance will be tied to the given Foo1 instance.

As others have pointed out, you can of cause make your Inner class static, in which case it does not contain an implicit reference to a Foo1 instance. Then you can simply call super(); in your Foo2 constructor.

2 Comments

Thanks.Your answer makes a lot of sense. So actually,foo1.super() is calling the Inner's constructor.
Yes, in the same way foo1.new Inner() creates a new Inner instance with foo1 as parent, foo1.super() calls the constructor of the new Inner instance with foo1 as parent. It is confusing that it looks like it is a call to the method super on foo1.
0

Make your inner class static. There is no instance from which to get a non static class definition

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.