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(){
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With