Java Basics

Where to create components

Component creation: declaration or constructor: Where should components be created with new, as part of the declaration, or in the constructor? This is a pretty small problem and I don't see much reason to prefer one style to the other, altho I've chosen to generally create them in the declarations.

Creating components in the declaration

Here's an example of declaring and creating a component in the declaration. It's a common style that is nice and brief.

    . . .
    private JTextField myHumanYearsTF = new JTextField(3);

    //====================================================== constructor
    public DogYearsGUI_1() {
        //... Create/initialize components
        myHumanYearsTF.setEditable(false) ;
        . . .

Issues with this:

  1. Some components will be created in the instance variable declaration area, but components that are stored in local variables will be created in the constructor. A slight inconsistency, which may be irrelevant. If they are all initialized in the constuctor, then there's only one place to look for initializations.
  2. Even if a component is created in the declaration, it is not uncommon to set additional attributes, which must be done in the constructor. This splits the code for the component into two places.
  3. The instance variables are typically the "most interesting" because they are used in multiple places. If they are all initialized at their point of declaration, it's easy to find all of these variables and their initial values.

Creating components in the constructor

    . . .
    private JTextField myHumanYearsTF;

    //====================================================== constructor
    public DogYearsGUI_1() {
        //... Create/initialize components
        myHumanYearsTF = new JTextField(3);
        myHumanYearsTF.setEditable(false) ;
        . . .

Not like C++

In C++ uninitialized instance variables usually have whatever value happens to already be in that part of memory, which can lead to extremely difficult to find bugs. Hence, in C++ it is recommended to always initialize instance variables at the point of declaration. This isn't as important in Java because instance variables are automatically initialized to null if not otherwise initialized. And during execution null pointer checking is performed, so this error is usually quickly found in the testing phase.

Therefore, the style of initializing in the declaration doesn't have the importance it did in C++.