0

I am reading two ways of creating a JFrame and i don't clearly undersand with is better or the differences:

import java.awt.*;
import javax.swing.*;

public class MyFramePanel {

    public static void main(String[] args) {

        JFrame myFrame = new JFrame("MyFramePanel");
....

And this one i find in some books:

import java.awt.*;
import javax.swing.*;

public class ButtonFrame **extends JFrame**{

    public ButtonFrame() {
        super("Button Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ...
        setVisible(true);
    }

    public static void main(String[] args) {
        ButtonFrame bf = new ButtonFrame();
    }
}

I am going to use the first one -i found it in Stackoverflow- but i wonder why the most of the books i am reading about Java are using the "extends JFrame" one.

Thank you so much and sorry for bothering if my question is stupid.

JJFS
  • 21
  • 2

1 Answers1

6

The first one is a good choice. Think about Composition over Inheritance.

To favor composition over inheritance is a design principle that gives the design higher flexibility, giving business-domain classes and more stable business domain in the long term.

If you won't use your MyFramePanel inside a JFrame, but instead in an Applet, it's easier to switch and better to maintain in the long term.

Martin Seeler
  • 6,874
  • 3
  • 33
  • 45