Wednesday, September 28, 2011

Inner Class calling example


package SCJP;

public class innerClass
{
public static void main(String[] args)
{
A a = new A();
a.displayA();

A.B b1 = a.new B();
b1.displayB();

A.B b2 = new A().new B();
b2.displayB();
}
}
class A
{
public void displayA()
{
System.out.println("Hi! I am in class A");
}
class B
{
public void displayB()
{
System.out.println("Hi! I am in class B");
}
}
}
Output =>
Hi! I am in class A
Hi! I am in class B
Hi! I am in class B
***********************************************
[NOTE: Bellow class has only difference with above one is in above one class "A" is outside the class"innerClass" where as for the bellow one class "A" is inside the class "innerClassToAccessOuterClass"]
package SCJP;

public class innerClassToAccessOuterClass
{
public static void main(String[] arun)
{
A a = new innerClassAccessOuterClass().new A();
a.diaplayA();
}
class A
{
void diaplayA()
{
System.out.println("Hi! I am in class A.");
}
}
}

Output =>
Hi! I am in class A.

No comments:

Post a Comment