简体   繁体   中英

Why can't object of nested class be used as a parameter of supertype constructor?

I have code like the following:

class A {
  final Object data;

  A(Object _data) {
      data = _data;
  }

  class B extends A {
      B() {
          super(new C());
      }

      class C { }
  }
}

I get following error message:

Cannot reference 'C' before supertype constructor has been called

I don't understand why it is not possible.

Are there any workarounds? I want data to be final and classes to be nested as they are in the code above (I don't want to create a different file for each class, because classes are quite small and in my real code it would be more logical for them to be nested)

With a simple nested class, it would be fine. However, you're creating an inner class of B , which means you're implicitly passing a reference to an instance of B - which would be this in this case, and you can't use this before super(...) completes.

Here's another example - read the comments:

class Base {
   Base(Object x) {}
}

class Outer extends Base {

   Outer() {
       super(new Nested()); // No problem
   }

   Outer(int ignored) {
       super(new Inner()); // Effectively this.new Inner()
   }

   Outer(boolean ignored) {
       super(new Outer().new Inner()); // Fine
   }

   Outer(long ignored) {
       super(new Nested(this)); // Explicitly passing this
   }

   static class Nested {
       Nested() {}

       Nested(Object ignored) {}
   }

   class Inner {
   }
}

The problem is that non-static inner classes need an instance of the outer class before they can be instantiated. That's why you can even access fields of the outer class directly in the inner class.

Make the inner classes static and it should work. In general it's a good pattern to use static inner classes instead of non-static. See Joshua Bloch's Effective Java item 22 for more information.

class A {

  final Object data;

  A(final Object _data) {
    data = _data;
  }

  static class B extends A {

    B() {
      super(new C());
    }

    static class C {
    }
  }
}

Hi sorry could not leave a comment.

I don't want to create a different file for each class, because classes are quite small

I had a professor that always said "There are never too small classes, only too big ones"

If you persist and still want the classes to be nested you can make class C static depending on your purpose of course. But I highly recommand to question your design.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM