Search code examples
javaclassextend

Access outer class's methods after extending inner class


I know I can access methods of outer class from within the inner class. Like the below class:

class outer {

    void outerMethod() {}

    class inner {

        void innerMethod() {
            outerMethod();
        }
    }
}

I want to know how can I do this if I extended the inner class?

I want to do the following:

class newClass extends outer.inner {

    void innerMethod() {
        outerMethod();
    }
}

I want to be able to access method() from newClass


Solution

  • Instance of non-static inner class requires existence of outer class instance which it will belong to.
    So to make class newClass extends outer.inner { compile you either need to

    1. make inner class static, and remove requirement of existence of outer class instance (but this will also limit your class a little)
    2. or ensure that inner will belong to some outer instance, which you can do by calling outerInstance.super() inside your constructor of your class which extends this inner class.

    In case of option 2, probably simplest solution would be explicitly passing instance of outer to your class like

    class newClass extends outer.inner {
    
        private outer o;
    
        public newClass(outer outerInstance) {
            outerInstance.super();
            this.o = outerInstance;
        }
    
        void innerMethod() {
            o.outerMethod();
        }
    }
    

    Now you can simply call your outerMethod() on passed instance of outer class.

    But remember that calling outerMethod is possible only when this method has proper visibility for your newClass. So despite the fact that inner is able to use any method of its outer class your newClass may not have access to it.