Static vs Non-Static Inner Classes:
There are main two differences:
- Non static inner class cannot have static data member and static member method.
- A static inner class can have instances but they don’t have enclosing instances! Which a non-static inner class have.
In the case of creating instance, the instance of non so static inner class is created with the reference of object of outer class in which it is defined……this means it have inclosing instance …….But the instance of static inner class is created with the reference of Outer class, not with the reference of object of outer class…..this means it have not inclosing instance.
class A {
static class B {
static int i = 0;
} // static-member class
class C {
// static int i =0;
} // non-static member class
}
public class InnerClasses {
public static void main(String st[]) {
A obj1 = new A();
A.C c = obj1.new C();// obj1 is enclosing instance
A.B b = new A.B(); // No enclosing instance required
}
}
No comments:
Post a Comment