A class like LocalDate
is immutable, it has a private constructor and each time we want an object of it, we have to call it's static methods, like LocalDate.now()
or LocalDate.of(year, month, day)
. These methods use new
keyword and call that private constructor, so each time a "new reference" is created. It is not a singleton class because we can have multiple objects at the same time.
But what about System
class? It looks like LocalDate
, it has a private constructor, but it doesn't have a static method to call that. This class, also is not abstract, so why java programmers wrote System
class like nobody can make an object of it? What is the design pattern behind it? Which classes act like this?
It has a private constructor which is never called, so there are never any instances (singleton would require one).
/** Don't let anyone instantiate this class */
private System() {
}
It is not abstract
public final class System {
System
is used more like a namespace. It's just a container for a bunch of static methods and constants.
Java does not allow you to put methods outside of a class so sometimes the result is a completely uninstantiated "class" like this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.