380
chapter 12
inner
classes
HeadFirst:
What makes inner classes important?
Inner object:
Where do I start? We give you a chance to
implement the same interface more than once in a class.
Remember, you can’t implement a method more than
once in a normal Java class. But using inner classes, each
inner class can implement the same interface, so you can
have all these different implementations of the very same
interface methods.
HeadFirst:
Why would you ever want to implement the
same method twice?
Inner object:
Let’s revisit GUI event handlers. Think
about it... if you want three buttons to each have a
different event behavior, then use three inner classes, all
implementing ActionListener—which means each class
gets to implement its own actionPerformed method.
HeadFirst:
So are event handlers the only reason to use
inner classes?
Inner object:
Oh, gosh no. Event handlers are just an
obvious example. Anytime you need a separate class, but
still want that class to behave as if it were part of another
class, an inner class is the best—and sometimes only—way
to do it.
HeadFirst:
I’m still confused here. If you want the inner
class to behave like it belongs to the outer class, why have
a separate class in the first place? Why wouldn’t the inner
class code just be in the outer class in the first place?
Inner object:
I just gave you one scenario, where you
need more than one implementation of an interface. But
even when you’re not using interfaces, you might need
two different classes because those classes represent two
different things. It’s good OO.
HeadFirst:
Whoa. Hold on here. I thought a big part of
OO design is about reuse and maintenance. You know, the
idea that if you have two separate classes, they can each
be modified and used independently, as opposed to stuffing
it all into one class yada yada yada. But with an inner class,
you’re still just working with one real class in the end, right?
The enclosing class is the only one that’s reusable and
separate from everybody else. Inner classes aren’t exactly
reusable. In fact, I’ve heard them called “Reuseless—
useless over and over again.”
Inner object:
Yes it’s true that the inner class is not as
reusable, in fact sometimes not reusable at all, because it’s
intimately tied to the instance variables and methods of
the outer class. But it—
HeadFirst:
—which only proves my point! If they’re not
reusable, why bother with a separate class? I mean, other
than the interface issue, which sounds like a workaround
to me.
Do'stlaringiz bilan baham: |