It is not clear what you are asking, but here are a few points:
- You cannot declare an instance variable in a constructor; you need to declare it as a type member (i.e. as a field).
- You can assign values ββto already declared instance variables in the constructor.
- You do not need to assign values ββto instance variables in the constructor; You can do it in ads.
When you write something like this:
public class Book{ private final Map<Character, SortedSet<String>> thesaurus = new HashMap <Character, SortedSet<String>>();
You then declared thesaurus as an instance variable of class Book , and you also initialized its value as new HashMap . Since this field is final , you can no longer set its value as something else (disallowing reflection-based attacks).
You can, if you want to choose this, move the initialization to the constructor. You can do this even if the field is final (depending on specific assignment rules).
public class Book{ private final Map<Character, SortedSet<String>> thesaurus; public class Book { thesaurus = new HashMap <Character, SortedSet<String>>(); }
Something similar happens sometimes when, for example, creating an initial value can raise a checked exception and therefore should be placed in a try-catch .
Another option is to initialize the fields in the instance initializer block:
private final Map<Character, SortedSet<String>> thesaurus; { thesaurus = new HashMap <Character, SortedSet<String>>(); }
And another option is to reorganize the mentioned instance initializer block into a helper method:
private final Map<Character, SortedSet<String>> thesaurus = emptyMap(); private static Map<Character, Sorted<String>> emptyMap() { return new HashMap <Character, SortedSet<String>>(); }
References
Related Questions
- Initialize final variable before constructor in Java
- Correct way to declare and set a private final member variable from a constructor in Java?
- In Java, can the final field be initialized from the constructor helper?
- Java - Is it possible to initialize final variables in a static initialization block?
- Best practice: initialize class fields in constructor or declaration?
polygenelubricants
source share