Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access outer class "super" from inner class in Java

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.

like image 986
pistacchio Avatar asked Oct 24 '11 11:10

pistacchio


People also ask

How do you access the outer class variable in an inner class?

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.

Can inner class access outer class methods Java?

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.

How do you call an outer class from an inner class?

Of your inner class is non static then create an object of innerClass. OuterClass out = new OuterClass(); OuterClass. InnerClass inn = out.


1 Answers

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 
like image 99
Lukas Eder Avatar answered Sep 18 '22 14:09

Lukas Eder