Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The placement of the new operator in a constructor or in the class body [duplicate]

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(){

    }

}
like image 827
gotta go fast Avatar asked Nov 10 '22 10:11

gotta go fast


1 Answers

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.

like image 176
Mureinik Avatar answered Nov 14 '22 22:11

Mureinik