Static & Static Factory Methods
Static belong to class NOT to the instance (object)
Static Variable: gets memory only once in the class area at the Time of Loading
Static Methods : Invoked without creating instance (eg. Math.pow())
- useful for memory management
- Static can be blocks, variables, methods & nested class (inner class)
can access static data member
Inheritance : Static methods of only parent is visible
Static method Restrictions
- Cannot use non-static data field or method directly
- Cannot use this and super on the static context
Static Initialization Blocks
What is Static Factory Method?
When a static method returns the same Class Object (reference type) of its own class, its called Static Factory Method
example
Runtime r = Runtime.getRuntime();
JAVA 9 Enhancement; of() method is static factory method
// shortcut way to create UNMODIFIABLE Collection Object (no add or remove works after it)
List<Integer> l = List.of(2, 3, 4, 5, 6, 7);//upto 10 elements, post which var-arg method
// but using var arg is costly
Optional<List<String>> strOptional = Optional.of(Arrays.asList("John","Doe"));
List<String> stringList = strOptional.get();