Reputation: 7050
I have made an Outer and an Inner class. Both these classes have variable int x
. How to access x
of Outer class in inner class. this.x
is not working.
class OuterClass {
int x,y;
private class InnerClass {
private void printSum(int x,int y) {
this.x=x;
this.y=y;
}
}
}
Upvotes: 5
Views: 3228
Reputation: 23483
If you want to do this you need to first instantiate the outer class, then the inner like so:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
int x,y,sum;
public static void main (String[] args) throws java.lang.Exception
{
//Create outer object
Ideone ideOne = new Ideone();
//instantiate inner object, and call method
Ideone.InnerClass ic = ideOne.new InnerClass();
ic.printSum(5,4);
}
private class InnerClass {
private void printSum(int x,int y) {
//reference the outer object instance
Ideone.this.x=x;
Ideone.this.y=y;
Ideone.this.sum = x + y;
System.out.println(Ideone.this.sum);
}
}
}
This has been tested here: http://ideone.com/e.js/DRIzSg
Output: 9
Upvotes: 1
Reputation: 684
Use OuterClass.this.x
; OuterClass.this
references the parent object (from whom the InnerClass
object is spawned).
Consider the following overshadowing example posted in the official Oracle tutorial:
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
with the output
x = 23
this.x = 1
ShadowTest.this.x = 0
x = 23
refers to the local variable of the method void methodInFirstLevel()
, this.x = 1
refers to the public field x
of the FirstLevel
inner-class, and ShadowTest.this.x = 0
refers to the public field x
of the ShadowTest
outer-class.
Upvotes: 0
Reputation: 578
Other way is to Make Outer class members as protected
public class OuterClass {
protected int x=10,y=20;
private class InnerClass {
private void printSum(int x1,int y1) {
x=x1;
y=y1;
}
}
}
Upvotes: -1
Reputation: 8358
You can try this :
private void printSum(int x,int y) {
OuterClass.this.x=x;
OuterClass.this.y=y;
}
Upvotes: 8