Clint7
Clint7

Reputation: 13

Calling a parent's inner class in a super call Java

So, I ran into a wall earlier. If I have a class Parent with an inner class SubParent like this:

public class Parent
{
   public class SubParent
   {
   }

   public Parent(SubParent sp)
   {
   }
}

Then I have a Child class which extends Parent like this:

public class Child extends Parent
{
   public Child()
   {
      super(new SubParent());
   }
}

Then I get a "error: cannot reference this before supertype constructor has been called" with an arrow pointing at the SubParent constructor.

Now, if I have SubParent as a separate class in it's own file, everything is fine. But I would like to have it as an inner class. Is there any way to do that?

Upvotes: 1

Views: 186

Answers (3)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

Your problem is that you are trying to create a SubParent very early in construction of the Child, before it is ready to use as "this" in an inner class creation. In addition to earlier suggestions, you could change Parent to have a parameterless constructor and a setter for its SubParent reference:

  public Parent(){

  }

  public void setSub(SubParent sp){

  }

The Child constructor can wait until after the super call to create the SubParent:

class Child extends Parent
{
   public Child()
   {
      setSub(new SubParent());
   }
}

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

An inner class instance requires an outer class instance to exist. At the point you are calling

super(new SubParent());

the SubParent constructor would have been called before an outer class instance has been created. You can't do this.

Either declare SupParent in its own file or make it static. What relationship are you trying to achieve anyway?

Upvotes: 2

Since your SubParent is not a static nested class, there's an implicit relationship between it and the Parent object it belongs to (in this case, also a Child object). It sounds like you're not needing the relationship an inner class provides; try making SubParent a public static class.

Note that there's a distinction between an inner class, which is not static (has a reference to an instance of its containing class), and a nested class, which is any class contained inside another class, whether static or not.

Upvotes: 1

Related Questions