javainheritanceanonymous-inner-class

How to call member variable in parent of outerClass from annonymous InnerClass


I have OuterClass extends ParentClass.
I'm trying to override annonymous InnerClass of ParentClass in OuterClass, and what I want to do is to call the member variable of ParentClass inside the overrided annonymous InnerClass.
Here is my code:

class ParentClass {
    int a;
    Runnable act;
    ParentClass() {
        act = new Runnable() {
            void run() {
                //codes
            }
        }
    }
}

class OuterClass extends ParentClass {
    OuterClass() {
        super();
        super.act = new Runnable() {
            void run() {
                // I want to call 'int a' here!!!
            }
        }
    }
}

Thanks for your help!!


Solution

  • This might do the trick for you:

    class ParentClass {
        protected int a;
        protected Runnable act;
        ParentClass() {
            act = new Runnable() {
                void run() {
                    //codes
                }
            }
        }
    }
    
    class OuterClass extends ParentClass {
        OuterClass() {
            super();
            super.act = new RunnableClass (a);
        }
    }
    
    class RunnableClass implements Runnable {
        private int a;
        public RunnableClass(int a) {
            this.a = a;
        }
    
        public void run() { //--- the code here
        }
    
    }
    

    I'm not sure if using protectedis the best approach as access rights for you, but my goal here is to let you free to create your own Runnable, with everything you need.