Java static nested class
A static class i.e. created inside a class is called static nested class in java. It cannot access non-static data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
Outer classes cannot be static, but nested/inner classes can be.
Whenever we run a class JVM instantiates an object. JVM can create a number of objects, by definition Static means you have same set of copy to all objects.So, if top class is static then whenever you run a program it creates an Object and keeps over riding on to the same Memory Location.
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
import java.io.PrintStream;
static class TestOuter1$Inner
{
TestOuter1$Inner(){}
void msg(){
System.out.println((new StringBuilder()).append("data is ")
.append(TestOuter1.data).toString());
}
}
class TestOuter2{
static int data=30;
static class Inner{
static void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter2.Inner.msg();//no need to create the instance of static nested class
}
}
No comments:
Post a Comment