I'm learning Java and as I know only abstract classes and interfaces cannot be instantiated. However documentation of java.lang.System says that it cannot be instantiated which is neither abstract nor an interface.
I haven't got any explanation of it. Can somebody please explain this ?
Moreover Can somebody create such classes ?
It's simple: It have no public Constructor.
You can do that yourself:
final public class Abc {
private Abc() {}
}
java.lang.System is java's version of a "static" class, meaning a class with only static methods and which does not require, or allow, an instance to be created before being used.
Since java doesn't allow the keyword "static" for class definitions (like C#), the best way to achieve such a static class is to make it's constructor private. For instance:
public final class System {
private System() { throw new UnsupportedOperationException(); }
public static void method1() { ... }
...other public static methods
}
This isn't fool proof, ie. checked by the compiler, but would restrict the class to only be created from within one of it's own methods, which the programmer is expected to know not to do (and will be reminded so by the exception if they should forget).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With