Re: How do i know which superclass to inherit from...
Joshua Cranmer wrote, quoted or indirectly quoted someone who said :
Traditionally, I make all of my custom panes extend JPanel; I can't
really think of a good case where JFrame needs to be extended: if I need
to make a powerful main window, I would likely just create a Main-ish
class that extends nothing and constructs the elaborate JFrame.
Roedy Green wrote:
Can you please enumerate the reasons you would not extend a JFrame or
JPanel? It seems to me when you do, you nicely encapsulate, with
getters and private variables. What are the advantages of doing it the
other way?
He already stated the main one: you don't need to extend JFrame. He obviously
analyzes his program as something that uses a JFrame, not /is-a/ JFrame.
Your question takes the opposite point of view from Joshua's statement. He
says,k "I can't really think of a good case where JFrame needs to be
extended." You ask for a good case where JFrame needs not to be extended. I
assert that burden of proof is on the case to extend.
Using a JFrame without extending it does not prevent you from having private
variables with accessor methods, nor from nicely encapsulating things.
It also locks you into using just the public interface of JFrame, insulating
you against possible changes in the API. This is good for the longevity of
your code.
There's little, if anything at all, you would want to do by extending a JFrame
that you cannot do by composing it. You would only extend JFrame to impose
custom public behaviors on the JFrame that it cannot already do itself.
Adding a JPanel is not a custom behavior, for example - JFrame already lets
you do that just fine.
As Joshua Bloch says in /Effective Java/
<http://java.sun.com/docs/books/effective/>
"Item 16: Favor composition over inheritance"
<http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA81&lpg=PA81>
I hope Joshua will also explain his reasoning.
--
Lew