Showing posts with label Jave InnerClass and OuterClass.. Show all posts
Showing posts with label Jave InnerClass and OuterClass.. Show all posts

Friday, August 6, 2010

Is OuterClass able to access the InnerClass Methods and Variables (Vice-Versa)?

In Main method both classes are unable to access the variables and methods but outside the Main method InnerClass has a right to access the OuterClass variables and Methods (even private also), but what about the OuterClass?
OuterClass has also right to access the InnerClass Variables and Methods...

How : innerclass_object and outerclass_obect
These two objects on the heap have a special bond, The inner can use the outer's variable (and vice-versa).

See the example:


public class OuterClass {
private String str;

// create the instance of innerclass...
InnerClass obj = new InnerClass();

private class InnerClass {
int i;

public int getI() {

// intialize the outerclass private variable
str = "aayushjain";
System.out.println(str);
return i;
}

public void setI(int i) {
this.i = i;

}

}

public void trial() {
System.out.println("hello i from outerclass");

// call the Inner Class methods
obj.setI(100);
System.out.println(obj.getI());
}

public static void main(String args[]) {
OuterClass obj_out = new OuterClass();

// unbale to access the innerclass methods.....
/* obj_out.getI(); */

OuterClass.InnerClass obj_inner = obj_out.new InnerClass();

obj_inner.setI(10);
System.out.println(obj_inner.getI());

// unable to access the outerclass methods..
/* obj_inner.trial(); */
obj_out.trial();

}
}