• Post Reply Bookmark Topic Watch Topic
  • New Topic

When to use member classes: From Bloch's Effective Java ch1  RSS feed

 
Campbell Ritchie
Marshal
Posts: 56530
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pallavi Sadit wrote: . . .
b) I never get to use member classes/interfaces and wonder if I am missing something regarding their usage. When should we go about using a member class or interface , what should be deciding factors whether to make a class/interface an independent one or a member?
I presume you are familiar with the Java Tutorials section about that?
Rule of thumb: can you consider whatever is in the inner class as part of the outer class. For example a Tree structure may have Nodes and the Nodes form part of the Tree, so the Node can be an inner class in the Tree class.
A Map can consist of Entries so a Map class can have an Entry inner class. If you look for Maps, you find that is almost exactly what happens: Map has Entry as a member. I said, “almost” because Map and Entry (more precisely Map.Entry) are interfaces rather than classes, but the same principles apply.

If you go through Bloch, he says that it is easier to use a public static nested class than a public inner class, so you will find that Map.Entry is public and static; if I have to write a Tree class I shall consider that nobody needs to know about Nodes outwith the class so I make Node a private instance member.
 
Campbell Ritchie
Marshal
Posts: 56530
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Split from this Bunkhouse Lounge thread.
 
Pallavi Sadit
Ranch Hand
Posts: 50
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell. So, what I understand from the explanation is that when a class needs to be used by only one class (putting in a better way- when used in context of only one other class) , like in the example of Map and Entry, we can make it a nested class. If we want to hide it from outside world, we can make it private.
 
Campbell Ritchie
Marshal
Posts: 56530
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree. There is a good explanation in the Java Tutorials link I posted yesterday; have you looked at it?
 
Pallavi Sadit
Ranch Hand
Posts: 50
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Campbell, went through it. That indeed explains very well.
 
Campbell Ritchie
Marshal
Posts: 56530
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!