0

In java, if you have a class (non static) and then an inner class inside it (also non static), how can you get a reference to the outer class object from the inner class?

public class Fish {
     public class Fin {
           Fish fish = _____;
     }
}

I want to store the Fish object in the variable fish in the Fin class.

Does anyone know?

omega
  • 40,311
  • 81
  • 251
  • 474

1 Answers1

4

You use

Outer.this

In your case

Fish.this
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Can you explain why you would use the class name when the class is not static. Also why doesn't something like `super.this` work? – omega Jun 10 '14 at 02:28
  • 1
    @omega `super` refers to the superclass, not the containing class, so changing its semantics for this one case would almost certainly be rejected during language design. `super.this` is also somewhat contradictory -- you can't try to get something from the superclass's namespace and the current object's namespace simultaneously. It doesn't make sense. – awksp Jun 10 '14 at 02:29
  • @omega Also, the class name here doesn't really have anything to do with static/nonstatic things; it's just a way to differentiate `this` for the inner class and `this` for the containing class, as inner classes have access to the containing class's methods. – awksp Jun 10 '14 at 02:37
  • 1
    @omega In addition, you can nest as many inner classes as you want, and refer to as many levels up in the nested-ness as you want with this syntax. – Sotirios Delimanolis Jun 10 '14 at 02:39