Static Inner classes?

Ever tried serializing the inner class object with non serializable
outer class? We cannot do this! By default compiler adds a reference
to the outer class in the inner class. Remember! we need to access
some attributes of outer class at times. This explicit referencing helps
at that time. When you try to serialize the inner class object you will
get an error.

Now what do we do if we want an inner class object to be serialized?
There is a way to do it. This is where you can use static inner class!.
A static inner class doesn't get a reference to the outer class when
compiled. Its treated as any other standalone class all together. When
an inner class is compiled its actually compiled into a class file with
name OuterClass$InnerClass.class where as the static inner class gets
its own seperate InnerClass.class file. This also meas that you cannot
access OuterClass members from static inner class since we no
longer have any reference to the outer class.

0 comments :