Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2006

Tip: Looking for answers? Try searching our database.

Benefits of Inner classes

Thread view: 
nospam - 26 Jan 2006 13:59 GMT
Hi..All,

   What are the exact benefits of inner classes? I tried going through
the books, but they explain how to define them. What do we achieve by
defining inner classes? When & why are they to be used?

Thanks a lot in advance.

Regards,

P~
bugbear - 26 Jan 2006 14:22 GMT
> Hi..All,
>
>    What are the exact benefits of inner classes? I tried going through
> the books, but they explain how to define them. What do we achieve by
> defining inner classes? When & why are they to be used?

1) Restricting anything's scope is always beneficial (modularity)

2) Anonymous inner classes make great "callbacks"

  BugBear
Chris Uppal - 26 Jan 2006 14:51 GMT
>     What are the exact benefits of inner classes?

In one sense, they have no benefits.  That's to say, there's nothing you can do
with inner, nested, or anonymous classes that you can't do -- and do quite
easily -- with "normal" top-level classes.  Indeed the whole inner-class thing
is just syntactic sugar for top-level classes.

The benefits are more about what you /can't/ do with them.  You can't "see"
them except as part of their containing class.  Or (in the case of anonymous
classes) see them at all.  Well, you /can/ see them, but you won't do so by
accident.  So, as bugbear, has already said, there's a benefit of
encapsulation, and there's also a benefit in reducing the overall clutter of
top-level names.

Also (even though it's mostly an illusion) creating a little inner or nested
class for some specific (but very limited) purpose doesn't /feel/ as much of a
heavy-weight operation as creating a top-level class, so programmers are more
likely to use little classes.  Bugbear also mentioned they are good for use in
callbacks; that's true, and the reason they are good for that is that creating
a top-level class for each callback would /feel/ like a complete pain (and
thinking of names for them would /be/ a pain ;-).

   -- chris
nospam - 26 Jan 2006 18:00 GMT
Hi..Bugbear/Chris,

  thanks a lot for the explanations. Continuing the thread, is there
any rule of thumb you use, to determine whether the classes need to be
"inner" ? It would be great if you can provide some real examples which
are easier to understand.

Except for the time spend on determining the class names & encapsulation
is there any benefit in performance, best practices, designing
methodology etc?

>>     What are the exact benefits of inner classes?
>
[quoted text clipped - 19 lines]
>
>     -- chris
Juha Laiho - 26 Jan 2006 18:17 GMT
nospam <nospam@nospam.com> said:
>Hi..Bugbear/Chris,
>
[quoted text clipped - 6 lines]
>is there any benefit in performance, best practices, designing
>methodology etc?

No benefit in performance, I'm pertty certain.

For me, inner classes tend to evolve by themselves -- it just starts to
make sense to separate some functionality of an existing class into
a class of its own. Then, if there really is no other use for the
separated class, I will let it remain as an inner class.

Then the other place are the already-mentioned anonymous inner classes
to be used in callback scenarios.
Signature

Wolf  a.k.a.  Juha Laiho     Espoo, Finland
(GC 3.0) GIT d- s+: a C++ ULSH++++$ P++@ L+++ E- W+$@ N++ !K w !O !M V
        PS(+) PE Y+ PGP(+) t- 5 !X R !tv b+ !DI D G e+ h---- r+++ y++++
"...cancel my subscription to the resurrection!" (Jim Morrison)

nospam - 26 Jan 2006 19:03 GMT
Hi...Juha,

    Thanks a lot. Where can I learn more about the concept "callback
scenarios / methods" .

Secondly, when a class gets instantiated , does the inner (non static)
class also get instantiated? If yes, won't it be a overhead ?

> nospam <nospam@nospam.com> said:
>> Hi..Bugbear/Chris,
[quoted text clipped - 17 lines]
> Then the other place are the already-mentioned anonymous inner classes
> to be used in callback scenarios.
Thomas Weidenfeller - 27 Jan 2006 08:30 GMT
>     Thanks a lot. Where can I learn more about the concept "callback
> scenarios / methods" .

The Swing GUI tutorial is full of them. Actually, one of the main
reasons given for inner classes was that they make GUI programming in
Java look a little bit nicer.

The Swing architecture TSC article is also a nice read

http://java.sun.com/products/jfc/tsc/articles/architecture/index.html

because it describes the architectural background. Callbacks are then
used to implement the communication required by the architecture. So in
this article you see WHY, and not only HOW things are done.

Oh, and if you want a general discussion, look for descriptions of the
Observer/Observable pattern. E.g. in the GoF book.

/Thomas
Signature

The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/

Juha Laiho - 30 Jan 2006 20:47 GMT
nospam <nospam@nospam.com> said:
>     Thanks a lot. Where can I learn more about the concept "callback
>scenarios / methods" .
>
>Secondly, when a class gets instantiated , does the inner (non static)
>class also get instantiated? If yes, won't it be a overhead ?

For your question on callbacks, you already got an answer.

As for instantiation, inner classes have no special behaviour, meaning
that they are in no way automatically instantiated - but instead you
have to instantiate them explicitly - just as you would do with any
top-level class.
Signature

Wolf  a.k.a.  Juha Laiho     Espoo, Finland
(GC 3.0) GIT d- s+: a C++ ULSH++++$ P++@ L+++ E- W+$@ N++ !K w !O !M V
        PS(+) PE Y+ PGP(+) t- 5 !X R !tv b+ !DI D G e+ h---- r+++ y++++
"...cancel my subscription to the resurrection!" (Jim Morrison)

zero - 26 Jan 2006 19:25 GMT
> Hi..Bugbear/Chris,
>
[quoted text clipped - 6 lines]
> encapsulation is there any benefit in performance, best practices,
> designing methodology etc?

As a simple rule of thumb I would suggest: if a class B is only used by
one other class A, and has no obvious re-use benifits (except of course
in conjunction with class A), then make class B a private (or package
access) inner class of A.

You may ask: if B is only used by A, why not eliminate the class and
just make all of its methods part of A?  Three main reasons:
encapsulation, readability, and making tighter classes.

A short example: suppose you're making a custom (reusable) JPanel that
uses customized JButtons.  These custom JButtons are not used in any
other components.

public class MyJPanel extends JPanel
{
  private JButton button;

  public MyJPanel()
  {
     button = new MyJButton();
  }

  // ...

  private class MyJButton extends JButton
  {
     public MyJButton(String text)
     {
        super(text);
        // customization code
     }

     // ...
  }
}

It makes sense to make this a private class because 1. the customization
code may be long, and could clutter up the MyJPanel constructor; 2. the
button is not used anywhere else; 3. someone reading the MyJPanel code
doesn't have to care that button is a custom button and not a normal
JButton.
George Cherry - 26 Jan 2006 23:04 GMT
> Hi..All,
>
[quoted text clipped - 3 lines]
>
> Thanks a lot in advance.

One benefit is that objects of an inner class can access
members of the containing class. Your books ought to
have some good examples of this special relationship
between objects of an inner class and objects of the outer
class. This visibility of members of the outer class can
be a huge benefit in communication between the inner
class and its containing class. If you can't find an example
of this advantage, ask again.

George
Roedy Green - 27 Jan 2006 00:29 GMT
>    What are the exact benefits of inner classes? I tried going through
>the books, but they explain how to define them. What do we achieve by
>defining inner classes? When & why are they to be used?

see http://mindprod.com/jgloss/innerclasses.html
and follow the links.

They are indispensible for event handling.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Stefan Ram - 27 Jan 2006 00:45 GMT
>see http://mindprod.com/jgloss/innerclasses.html
>They are indispensible for event handling.

 I am just removing them from my course, because I want to
 start Swing as early as possible. Removing inner classes,
 I save the time to explain them, and thus can start real
 work with Swing earlier. I also reduce the number of
 different types of entities a beginner has to learn.

 Instead of using an inner class, I write, for example:

this.button.addActionListener( controller );

 with an external class.

class ButtonController
implements java.awt.event.ActionListener
{ public void actionPerformed
 ( final java.awt.event.ActionEvent actionEvent )
 { java.lang.System.out.println( "Hello event!" ); }}
James - 27 Jan 2006 01:51 GMT
P~

The MOAT framework makes some user of anonymous and inner classes and
my provide good examples
of how and when they should be used.

The generator is a good place to start to make some code to see.

Rgs, James.
http://www.jamesladdcode.com/moat
Thomas Weidenfeller - 27 Jan 2006 08:35 GMT
>   I am just removing them from my course,

I understand your reasons, but I typically don't like such things. I
always liked it when my professors taught me the real-world thing and
usage, and not some "kuschelweich" version which, when used or applied
in the real world, made me look stupid or incompetent.

And I like to work with people who know the real stuff, not some fluffy
feel-good version of it. In case of inner classes and GUIs I would be
very surprised if I would meet someone who claims to know Java GUI
programming but doesn't know or use inner classes.

/Thomas
Signature

The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/

Stefan Ram - 27 Jan 2006 13:23 GMT
>And I like to work with people who know the real stuff, not
>some fluffy feel-good version of it.

 Writing a non-inner controller class for a GUI-componenten is
 not real stuff?

>In case of inner classes and GUIs I would be very surprised if
>I would meet someone who claims to know Java GUI programming
>but doesn't know or use inner classes.

 My classes are for beginners, who might learn Java as their
 first programming language. The classes have a very limited
 length of time. With this constraints, it is not possible to
 reach a stage where the learners could claim "to known Java
 GUI-programming" at the end, independent of the choices made.
 The best thing one could do is to make the learners enjoy
 working with Java, so that they will continue learning Java
 after the end of the course, which will then lead them to get
 to know many topics that are not part of the course, such as
 inner classes.
Josh Falter - 27 Jan 2006 14:07 GMT
To further the point a few others have made, the only place that I
consistently use inner-classes are in my event handlers, since they are
*always unique to that class.

That being said, there are two different styles you see.
1.) Using anonymous Objects as Listeners i.e.
SomeButton.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent ae)
  { /* Functionality */ }
}

or Using an inner class that implements the ActionListener i.e.
class ButtonHandler implements ActionListener
{
  public void actionPerformed(ActionEvent ae)
  { /*functionality*/}
}

and then instanstiating and adding the listener somewhere in the public
class body...
ButtonHandler bHandler = new ButtonHandler();
SomeButton.addActionListener(bHandler);

I definitely prefer the second method, especially if I have multiple
Components that will need the same type of Listener, but regardless,
both are uses of inner classes to solve the same common issue.

The reason that either of these are great cases for inner classes is
because each class will usually have a unique way it needs  to handle
these events, thus eliminating any reason to give access to them to
other classes.
Roedy Green - 27 Jan 2006 14:42 GMT
> My classes are for beginners, who might learn Java as their
>  first programming language.

the problem is without anonymous inner classes, you set up only one
listener per panel. It has to handle all the components. It simpler to
set up one per component with anonymous classes. Then you don't have
to guess who sent you the event.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Stefan Ram - 27 Jan 2006 14:58 GMT
>the problem is without anonymous inner classes, you set up only
>one listener per panel. It has to handle all the components.

 One can construct a new instance of a named external class for
 each panel and pass the panel as an argument of the instance
 creation expression.
bugbear - 27 Jan 2006 15:44 GMT
>>the problem is without anonymous inner classes, you set up only
>>one listener per panel. It has to handle all the components.
>
>   One can construct a new instance of a named external class for
>   each panel and pass the panel as an argument of the instance
>   creation expression.

Yes - it's a little more typing, but it does
reduce the number of new concepts for the neophytes.

  BugBear
George Cherry - 28 Jan 2006 18:40 GMT
>>    What are the exact benefits of inner classes? I tried going through
>>the books, but they explain how to define them. What do we achieve by
[quoted text clipped - 4 lines]
>
> They are indispensible for event handling.

Indispensible? Very convenient, yes; but not indispensible,
I think.

George


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.