Frage

This might be a stupid question, but does it matter if you iniate a new object in the constructor for a class or if you have the iniation of the object/variables in the class body instead?

public class MyFrame extends JFrame {

    private JButton button1;
    private JButton button2;

     public MyFrame(){

        button1 = new JButton("Button1");
        button2 = new JButton("Button2");
    }

}

versus

public class MyFrame extends JFrame {

    private JButton button1 = new JButton("Button1");
    private JButton button2 = new JButton("Button2");

     public MyFrame(){

    }

}
War es hilfreich?

Lösung 2

Initialising objects in the class body works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate.

Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks

More info here: http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Andere Tipps

Both these samples of code will execute the same way. Java first calls all the iniline initializers, and then the constructor.

Personally, I prefer having all the relevant code in the constructor, where I can see it in a single glance. Additionally, having all the code in the constructor and not inline gives me the freedom of initializing the members in different ways if I have different constructors. The flipside of this argument, of course, is that if you have multiple constructors and always want to initialize some of the members in the same way, you'd have to either duplicate code, extract this common code to another method, or call one constructor from another, which could be annoying.

Ultimately, it's a styling decision, no more, no less.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top