Why can't outer classes extend inner classes?

前端 未结 2 1451
半阙折子戏
半阙折子戏 2021-02-09 05:44

Why can\'t I do this/is there a workaround to accomplish this:

package myPackage;

public class A {
    public class B {

    }
}



        
2条回答
  •  一个人的身影
    2021-02-09 06:31

    You can easily extend nested static classes

    Update: You've mentioned that you don't want this first solution, but the phrasing of the question may lead people to it who are willing to have the inner class be static, so I'll leave this in the hopes that it's useful to them. A more proper answer to your exact question is in the second section of this answer.

    You can, but the inner class has to be static, because if it's not, then every instance of the inner class has a reference to the enclosing instance of the outer class. A static nested class doesn't have that reference, and you can extend it freely.

    public class Outer {
        public static class Inner {
    
        }
    }
    
    public class InnerExtension extends Outer.Inner {
    
    }
    

    But you can also extend nested non-static classes

    package test;
    
    public class Outer {
        public class Inner {
            public String getFoo() {
                return "original foo";
            }
        }
    }
    
    package test;
    
    public class Extender {
        public static void main(String[] args) {
            // An instance of outer to work with
            Outer outer = new Outer();
    
            // An instance of Outer.Inner 
            Outer.Inner inner = outer.new Inner();
    
            // An instance of an anonymous *subclass* of Outer.Inner
            Outer.Inner innerExt = outer.new Inner() {
                @Override
                public String getFoo() {
                    return "subclass foo";
                }
            };
    
            System.out.println("inner's class: "+inner.getClass());
            System.out.println("inner's foo: "+inner.getFoo());
            System.out.println();
            System.out.println("innerExt's class: "+innerExt.getClass());
            System.out.println("innerExt's foo: "+innerExt.getFoo());
        }
    }
    
    inner's class: class test.Outer$Inner
    inner's foo: original foo
    
    innerExt's class: class test.Extender$1
    innerExt's foo: subclass foo
    

提交回复
热议问题