Advertisement
//Java - Creating an Inner class within an Outer class
//Outer class
class OuterC
{
private int a=10; //variable of an outer class.
//Inner class within an Outer class.
public class InnerC
{
public void name() //method of an Inner class.
{
System.out.println("InnerC class");
}
}//Inner class ends
}//Outer class ends
//Java - Creating an object of inner class from within a non-static method of outer class
class OuterC
{
private int a=10;
public void outerMethod()
{
InnerC innerOb = new InnerC();
innerOb.innerMethod();
}
public class InnerC
{
public void innerMethod()
{
System.out.println("Method of Inner Class is invoked");
System.out.println("Inner class accessing instance variable of Outer Class, a = "+ a);
}
}
public static void main(String... ar)
{
OuterC outerOb= new OuterC ();
outerOb.outerMethod();
}
}
Method of Outer Class
Method of Inner Class
Accessing member of Outer class from inner class, a = 10
Advertisement
//Java - Creating an object of inner class from within a static method of outer class -:
public class OuterC
{
private int a=10;
public void outerMethod()
{
System.out.println("Method of Outer Class");
}
class InnerC
{
public void innerMethod()
{
System.out.println("Method of Inner Class");
System.out.println("Accessing member of Outer class from inner class, a = " + a);
}
}
//Static method of OuterC class
public static void main(String... ar)
{
//Creating an object of outer class
OuterC outerOb = new OuterC();
//Calling a method of outer class
outerOb.outerMethod();
//ob.innerMethod(); // won't work
//Creating an object of inner class.
OuterClass.InnerC innerOb = outerOb.new InnerC();
//Calling a method of inner class
innerOb.innerMethod();
}
}
Method of Outer Class
Method of Inner Class
Accessing member of Outer class from inner class, a = 10
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement