Wednesday, May 15, 2013

why static is not allowed in inner class

why static is not allowed in inner class or why static final is allowed in inner class

The idea behind inner classes ( non static inner class) is to operate in the context of the enclosing instance. Somehow, allowing static variables and methods contradicts this motivation.
http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.1.3

Inner class are like an instance attribute of enclosing object. Also static means to work without instance at first place.

So it's doesn't make sence to allow staic feature in inner classes.

Let take this example:

 class pardeep{
   public String name;
  }

If you create two instance of this pardeep

pardeep a= new pardeep();
a.name="kumar";

pardeep b=new pardeep();

b.name="kumarOne";

It is clear the each has own value for the property name.


The same happens with inner class, each inner class instance is independent of the inner class instance.


So if you try to create counter(static) attribute , there is now way to share the value across two different instances.


class Pardeep {

  public string name;
  class kumar{
    static counter;
  }
}

when you create two instance a and b , what would be the correct value for the static variables counter? It is not possible to determine, because existence of

Kumar class depends completely on each of the enclosing object.
That why static is not allowed in inner.

Note: This is also the reason that when class is declared static, it doesn't need any living instance to live itself.


If this counter is constant, then there will be no problem because value is not going to be changed.

That why final make them(counter) constant once initilazed, is a compile time contant value.
i.e, final static counter;
That why final static is allowed in inner class


If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...

No comments:

Post a Comment