What is Static inner class?

-The enclosing class is static.
Accessing a static member of inner class:
In the same class:
class demo
{
static class x
{static int i=10;}
public static void main(String[] args){
System.out.println(demo.x.i);
}};

In different class:
class demo1
{
static class x
{static int i=10;}
};
class demo
{

public static void main(String[] args){
//demo1.x obj=new demo1.x();
System.out.println(demo1.x.i);
}};
Accessing non static variable of inner class:
In the same class:
class demo
{
static class x
{int i=10;}
public static void main(String[] args){
x obj=new x();
System.out.println(obj.i);
}};
In different class:
class demo1
{
static class x
{int i=10;}
};
class demo
{

public static void main(String[] args){
demo1.x obj=new demo1.x();
System.out.println(obj.i);
}};

Key Points:
❑ Static nested classes are inner classes marked with the static modifier.
❑ A static nested class is not an inner class, it's a top-level nested class.
❑ Because the nested class is static, it does not share any special relationship
with an instance of the outer class. In fact, you don't need an instance of the
outer class to instantiate a static nested class.
❑ Instantiating a static nested class requires using both the outer and nested
class names as follows:
BigOuter.Nested n = new BigOuter.Nested();
❑ A static nested class cannot access non-static members of the outer class,
since it does not have an implicit reference to any outer instance (in other
words, the nested class instance does not get an outer this reference).

No comments:

Post a Comment