MY mENU


Thursday 9 February 2012

Innerclass and Outerclas

Accessing Innerclass and Outer Class Members:


Inner class member are not avaiable outside of the class.But you can access outer class member inside the inner class.

if your member variable are same in inner and outer class then use this keyword with corresponding class name.




We can use all the modifiers for Inner Classes. For example, we can use the access specifiers — private, public, and protected — to restrict access to Inner Classes, just as we do to class members (methods and variables).


see the example given below

public class InnerClassTest {

private int x;
public class Inner{

private int y;
private int x = 5;
public void innerMethod(){
System.out.println("y is " + y);
System.out.println("x is " + this.x);
System.out.println("x is " + InnerClassTest.this.x);
}
}

public void outerMethod(){
// System.out.println("y is " + y);//wrong bcoz y is a member of inner class
}
public static void main(String arg[]){
InnerClassTest ic = new InnerClassTest();

InnerClassTest.Inner in = ic.new Inner();
in.innerMethod();
}
}

No comments:

Post a Comment