June 2018
Beginner
722 pages
18h 47m
English
There is a similar solution for static field initialization. The static block can include the code necessary to generate values that have to be used for static field initialization:
class SomeClass{ public String getThatString(){ return "that string"; }}public class ManageCollections { private static Set<String> set = new HashSet<>(); static { SomeClass someClass = new SomeClass(); set.add(someClass.getThatString()); set.add("another string"); } public static void main(String... args){ System.out.println(set); //prints: [that string, another string] }}
Since set is a static field, it cannot be initialized in a constructor because a constructor is called only when an instance is created, while a static field can ...
Read now
Unlock full access