Tuesday, 2 July 2013

Properly Accessing your Outer Class

Recently, during my work, a colleague indicated a way to make it obvious that a variable used in an Inner class, belonged to the outer class. In order to prevent being ambiguous.

package mrbear;
/**
*
* @author MrBear
*/
public class MrBear
{
private String world = "The world.";
public class FirstInner
{
public void printWorld()
{
// ambiguous
System.out.println(world);
}
}
public class SecondInner
{
public void printWorld()
{
// not ambiguous
System.out.println(MrBear.this.world);
}
}
}
view raw MrBear.java hosted with ❤ by GitHub

I didn't know that could work.

References

Nested Classes - The Java Tutorials
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

No comments:

Post a Comment