Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I found this code and I want to understand why the programmer did this instead of continuing the declaration in the same line?

Java
public class Program {
    private Map<Integer, String> abc1;
    private Map<Integer, List<String>> abc2;
    private Function main;
    private StringBuilder Code1;

    public Program() {
        code 1 = new StringBuilder();
        abc1 = new HashMap<>();
        abc2 = new TreeMap<>();
    }
}


What I have tried:

I tried this

Java
private Map<Integer, String> new HashMap<>() ;


but they are work fine, is there any difference between the two ways?

Thank you in advance
Posted
Updated 18-Feb-20 3:22am
Comments
Maciej Los 18-Feb-20 9:15am    
Ask an author of above code...

1 solution

The only difference is that initializing fields upon declaration, as in
C#
private Map<Integer, String> abc1 = new HashMap<>();
makes things a bit easier (this is a personal opinion which could be highly argued since it mostly depends on the context). Whatever constructor you will call, you are sure that these fields will be properly initialized.

Whereas, when you initialize those fields inside a constructor, then you must make sure that the fields are properly initialized while using other constructors, too.
C#
// Declaration without initialization
private Map<Integer, String> abc1;

// Default initializer
public Program()
{
   abc1 = new Map<Integer, String>();
}

// Initialize from parameter
public Program(Map<Integer, String> map)
{
   abc1 = map ?? new Map<Integer, String>();
}

// Initialize by calling default constructor
public Program(double someOtherField) : this()
{
   // ...
}
 
Share this answer
 
v2
Comments
Hisham-Developer 18-Feb-20 9:35am    
I understand it very clear now.
The programmer is only having one constructor so it is better to initialize it outside the constructor since we don't have another constructor.
phil.o 18-Feb-20 9:37am    
Whatever the way, if the fields are properly initialized, it is appropriate.
CPallini 18-Feb-20 10:36am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900