October 2019
Intermediate to advanced
434 pages
11h 54m
English
It's possible to modify the visibility of a constructor. This is sometimes desirable in order to limit how or what can instantiate a class. A common example of this in Java would be the factory pattern in which the instantiation of a class can only be performed by some factory method.
For example, to make a primary constructor private, we can add the private keyword before the constructor keyword when defining the private constructor:
class School private constructor(val name: String)
In this example, School can longer be instantiated because its only constructor is private. To modify the visibility of a secondary constructor, we once again add the visibility modifier before the constructor keyword:
class School private ...
Read now
Unlock full access