How can I access outer class' super
from an inner class?
I'm overriding a method to make it run on a different thread. From an inline Thread, I need to call the original method but of course just calling method()
would turn into an infinite recursion.
Specifically, I'm extending BufferedReader:
public WaitingBufferedReader(InputStreamReader in, long waitingTime) { [..] @Override public String readLine() { Thread t= new Thread(){ public void run() { try { setMessage(WaitingBufferedReader.super.readLine()); } catch (IOException ex) { } } }; t.start(); [..] } }
This somewhere gives me a NullPointerException I'm not able to find.
Thanks.
If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.
Of your inner class is non static then create an object of innerClass. OuterClass out = new OuterClass(); OuterClass. InnerClass inn = out.
Like this:
class Outer { class Inner { void myMethod() { // This will print "Blah", from the Outer class' toString() method System.out.println(Outer.this.toString()); // This will call Object.toString() on the Outer class' instance // That's probably what you need System.out.println(Outer.super.toString()); } } @Override public String toString() { return "Blah"; } public static void main(String[] args) { new Outer().new Inner().myMethod(); } }
The above test, when executed, displays:
Blah Outer@1e5e2c3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With