Herbert Schildt in The Complete Reference Java 2 says,"Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used."
Can we use static nested classes practically? If yes, please demonstrate it with help of an example program.
I don't think that they can be useful. So I am wondering whether they can be practically implemented or not. I still do not know whether they have some practical application or they are just a theoretical concept. Someone please help.
> Can we use static nested classes practically?
Look at the source code of the 'Entry' inner class of 'HashMap'. The source can be found in the JDK directory in src.zip.
They can be useful as small data structures or "helper" objects that only have applicability in the context of their enclosing class. S.O.S. posted an example of such a case above. The 'Entry' is really only useful with the HashMap. It could be published as a full public class, but if it is not used by other classes then it just clutters the API. As a static inner class of HashMap, its usage is clearly scoped.
one word of caution: don't trust anything you read in Herb's book unless and until you find it confirmed elsewhere.
It's not all bad, but there is a large number of glaring errors caused by his fundamental misunderstanding of some core concepts of the Java language and its runtime environment.
While he is right that static nested classes have restrictions, they can be useful nonetheless. Particulary they can be useful when employed in combination with nested interfaces inside interfaces and abstract classes to provide callback mechanisms.
Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.
This thread is more than three months old
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.