1

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!!

  • you can make it (the variable you want to access) protected, create a getter (`get` method) for the variable) with protected or public access... – Leonardo Alves Machado Jun 07 '19 at 16:41
  • However, looking at your code, the `Runnable` object you are creating there is not related to the `ParentClass` - neither to `OuterClass`... This might be your issue here. You might want to create a class that implements `Runnable` and that has a constructor that receives the variable you want – Leonardo Alves Machado Jun 07 '19 at 16:44
  • @LeonardoAlvesMachado, what do you mean by "the Runnable object you are creating there is not related to the ParentClass -neither to OuterClass"? – Dongwook Shin Jun 07 '19 at 16:50
  • I rather suggest you declare "act" to be protected (read about that keyword) and simply access it directly. Or you make it private, but a protected setter method for it. – GhostCat Jun 07 '19 at 16:52
  • 1
    @LeonardoAlvesMachado Ah, I understand. Thank you so much!! – Dongwook Shin Jun 07 '19 at 16:55
  • @GhostCat, but how can I access it directly? I tried "a", "super.a", "ParentClass.this.a" but didn't work... – Dongwook Shin Jun 07 '19 at 17:04
  • I suggest you stop wasting your time with. Focus on doing things the right way. Research the usage of protected, instead of trying to use something that isn't intended to be used that way. – GhostCat Jun 07 '19 at 17:33

1 Answers1

0

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.

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53