It's not clear what you're asking, but here are some points:
- You can't declare an instance variable in a constructor; you have to do declare it as a member of the type (i.e. as a field).
- You can assign values to already declared instance variables in a constructor.
- You don't have to assign values to instance variables in a constructor; you can do it at the declarations.
When you write something like this:
public class Book{
private final Map<Character, SortedSet<String>> thesaurus =
new HashMap <Character, SortedSet<String>>();
//...
}
Then you've declared thesaurus
to be an instance variable of class Book
, and you also initialized its value to be a new HashMap
. Since this field is final
, you can no longer set its value to be anything else (barring reflection-based attacks).
You can, should you wish to choose so, move the initialization into the constructor. You can do this even when the field is final
(subject to various definite assignment rules).
public class Book{
private final Map<Character, SortedSet<String>> thesaurus;
public class Book {
thesaurus = new HashMap <Character, SortedSet<String>>();
}
//...
}
Something like this is done sometimes when e.g. the creation of the initial value may throw a checked exception, and therefore needs to be put in a try-catch
block.
Another option is to initialize fields in an instance initializer block:
private final Map<Character, SortedSet<String>> thesaurus;
{
thesaurus = new HashMap <Character, SortedSet<String>>();
}
And yet another option is to refactor said 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