Nested-Inner class in java

It is possible to define a class within another class.
The scope of the nested class is within the enclosing class.
There are two type of nested classes in Java.
The nested classes which are static are simply called the Nested classes
while the non-static ones are called Inner classes.
Example of Inner Classes.

class outer_class{
public static void main(String args[]){
outer_class outer_object=new outer_class();
}

inner_class inner_object=new inner_class();
int ffff=inner_object.z;

private int x;
public int y;
class inner_class{
void fn(){
x=10;
y=9;
}
private int z;
}

}

In inner classes even the private members of the enclosing class are
directly accessible to the enclosed class.And also the private members
of the enclosed class is accessable through the object of the enclosed class
in the enclosing class.
Note:Inner classes cannot have static members. Static declarations are
for top-level entities,or for the class as a whole, not an instance.
And also we cannot declare any static variable in any function.
Example of Static Classes.

class outer_class{

static class inner_class{

}

}

As it is the static class, we cannot access the members of the outer class directly.

So we have to access them using the object.

Note:There is no such modifier static for the class which is not enclosed
in another class

class dev{
public static void main(String args[])
{
deven.fn();//non-static variable this cannot be referenced
//from the static context
}
}

static class deven{ //Modifier static not allowed here

void fn(){
System.out.println("Deven");
}
}

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s