Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Extend JFrame or encapsulate?  RSS feed

Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey all,

I've still not decided whether to extend JFrame or have it as a private member variable (of my MainWindow class... which I may rename, but that's by the by)

Most examples on the web and theads ont here and other formum that I've seen seem to say extending JFrame is the best way.

Arguments for extending JFrame:
  • Other classes will be able to use all the public methods of JFrame, thus making your class more flexible.
  • The class does seem to pass the "IS-A" test for a JFrame. It represents a frame on the screen.

  • Arguments for private encapsulation:
  • Other classes will NOT be able to access the public methods of JFrame, so you do not have to think about what will happen if other classes use them.
  • In either case, I will probably have member variables for the various JButtons and JMenuItems, since I will have "hook" methods to register listeners for them. It seems a bit messy to have them both as member variables, and using .add() to add them to the frame.
  • As far as I see it, OOP principles mean that JFrame should be extended when adding some sort of extra JFrame type behaviour. I'm not sure this is the case here. The JFrame is simply being used to display (via add()) the components on the screen. Is this an argument for the "HAS-A" relationship?

  • Does anyone have any comments on my arguments, or even any more arguments for either side? I've searched, but am unable to find much. Links to FAQs or other threads where I may get help gratefully accepted.

    author and jackaroo
    Marshal Commander
    Posts: 12167
    C++ Firefox Browser IntelliJ IDE Java Mac Oracle
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi Michal,

    I think you have to go back to your basic concept of whether your new object will be a new form of JFrame, or is it just using the JFrame (the old "is a" versus "has a" issue).

    Are you creating a new JFrame that you (and others) may want to use time and time again? For example, your version of JFrame will always have a blue frame, will always default to exit on close, etc.? And then you can use this to ensure that all your frames are going to have the same look and feel?

    Or are you using a JFrame to hold your buttons, tables and other widgets, in which case it is highly unlikely that anyone would want to use your layout and widgets.

    Hope this helped.

    Regards, Andrew
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!