JCoder
JCoder

Reputation: 189

Java Inner Classes: extends keyword for multiple

I have multiple levels of inner classes. The extend keyword works for the first sub-level, but not the second. Meaning:

public class A{
       .........
    public class B extends A{
           ..........
        public class C extends B{
             ........
        }
    }
}

This gives me an error for public class C extends B{. It says:

No enclosing instance of type A is available due to some intermediate constructor invocation.

Why am I getting this error and how can I fix it? I thought the default constructors would deal with this.

Upvotes: 5

Views: 172

Answers (2)

Others
Others

Reputation: 3013

You are using non-static subclasses, which require references to outer instances. If you don't need their non-staticness just add the static keyword to the inner classes' definitions. I'm not sure why the given example isn't working for you though.

Upvotes: 0

Sergey Fedorov
Sergey Fedorov

Reputation: 2169

Your code is legal and should work. The fact you've got the error means one of:

  1. You've posted not all the code
  2. You use broken/modified jre.

I looked at your error that states

No enclosing instance of type A is available due to some intermediate constructor invocation.

So I suppose there are some constructors declared in your code. Possible reason of your failure is you declared constructor with parameters for class A but haven't done that for B and C. Explanation from spec:

It is a compile-time error if a default constructor is implicitly declared but the superclass does not have an accessible constructor that takes no arguments and has no throws clause.


Another possibility is that you already have A or B class in your package or you have imported A or B class from another package. The error can be misleading if compiler doesn't know what class do you extend.

Upvotes: 1

Related Questions