Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System class in Java

Tags:

java

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 ?

like image 233
bitsbuffer Avatar asked Sep 18 '26 16:09

bitsbuffer


2 Answers

It's simple: It have no public Constructor.

You can do that yourself:

final public class Abc {
   private Abc() {}
}
like image 94
J-16 SDiZ Avatar answered Sep 21 '26 04:09

J-16 SDiZ


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).

like image 24
idWinter Avatar answered Sep 21 '26 04:09

idWinter