aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "inner classes" Watch "inner classes" New topic
Author

inner classes

ashok khetan
Ranch Hand

Joined: Jul 29, 2001
Posts: 153
If a non-static inner class has a member variable that has exactly same name as of its enclosing class then how can we access the member variable of the enclosing class in a method of inner-class?
If we write this.x or simply x then it displays the x of inner class both the times.
Gaja Venkat
Ranch Hand

Joined: Aug 10, 2001
Posts: 50
Hi:
If the enclosing class' member variable, say x, is static then it can be referred to in the inner class' method by enclosingclassname.x
If the enclosing class' member variable x is not static, then guess, its instance must be used to refer to x.
In the following code, both x and y appear in both Outer & Inner. But in Outer, y is static and x is not static. So in inner class, o.x and Outer.y are used to refer to x and y of the Outer class respectively. The variable z appears in Outer only, so it can be referred to as just z in inner class' method.

The output is as follows:
x 20
this.x 20
o.x 10
y 20
Outer.y 10
z 10
Hope this helps,
Gaja.
Guy Reynolds
Ranch Hand

Joined: Oct 27, 2000
Posts: 61
The only way I know of is to pass the inner class a reference to the outer class like:
<code>
class OuterClass
{
class InnerClass
{
void method()
{
System.out.println( outer.memberVariable );
}

String memberVariable = "Inner";

public InnerClass( OuterClass outer )
{
this.outer = outer;
}

private OuterClass outer;
}

String memberVariable = "Outer";
public static void main( String[] args )
{
OuterClass outer = new OuterClass();
outer.new InnerClass( outer ).method();

}
}
</code>
This will print out "Outer".

Christy Smith
Greenhorn

Joined: Aug 15, 2001
Posts: 26
The easy answer is :
enclosingClassName.this.x
Guy Reynolds
Ranch Hand

Joined: Oct 27, 2000
Posts: 61
I guess that is easier.
Ashik Uzzaman
Ranch Hand

Joined: Jul 05, 2001
Posts: 2370

Guy, very tricky example but without explanation...
------------------
azaman


Ashik Uzzaman
Senior Member of Technical Staff, Salesforce.com, San Francisco, CA, USA.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: inner classes
 
Similar Threads
? inner class or local class member
Q on variable Initialization
Method local inner classes - conclusion
Static method inside an inner class.
Where Can I Read about Non-Static Inner Classes?