Search code examples
javainheritanceinner-classessuperclass

Does a nested inner class automatically inherit from superclass of outer class in java?


Say I have an Outer class A and it's nested Inner Class B. A is subclass of C. Then is B also a subclass of C? Since B can access all private members of A and thus that(public and protected) of it's superclass, so I think B becomes a subclass of C.

Is my line of thinking right?

Any help is highly appreciated.


Solution

  • Here's what you seem to be describing:

    class C {} 
    class A extends C {
        static class B {}
    }
    

    Being a nested class in A does not make B a subclass of C. Access to members is not the defining characteristic of being a subclass.

    Suppose you try to assign an object of type B to a variable of type C.

    C c1 = new A(); // OK -- A is a subclass of C
    C c2 = new A.B(); // Not OK
    

    If B were a subclass of C, the latter would be a legal assignment. But it is not.