简体   繁体   中英

Why don't we have to create object of System or Math classes in java and use them directly?

We use System.out.println without instantiating it or creating object of it. Same goes to Math class and many others (I guess). Is there something special about these classes? Can we use the classes and methods declared within those classes in same fashion? Please help.

This is something called 'static' method. In order to invoke static method, you do not need to have an instance of the class.

This also has other side effects such as non-existing 'this' and thus static methods cannot invoke instance methods.

This is mostly used for some sort of utility classes which are often stateless.

Math is a good example for it.

I suggest to read a bit about static methods and static in Java in general.

You don't have to create objects for the System and Math classes because the methods and variables in those classes are static . This means that they belong to the class itself, not to instances of the class.

For reference see:

Why don't we have to create object of System or Math classes in java and use them directly?

Because the methods of Math are declared as static methods, and because System.in / System.out / System.err are static variables.

Is there something special about these classes?

No. Any variables or methods that are declared as static will behave that way.

Can we use the classes and methods declared within those classes in same fashion?

I don't really understand what you are asking there. But, if you are asking if you can create an instance of Math or System so that you can do something like this:

    Math myMath = new Math();
    myMath.min(1, 2);
  1. No, you can't. Neither of those classes has a public constructor, so you can't new them.

  2. And if you could do that, it would be really bad style!

Reference:

We don't instantiate every other class or method because the JVM(Java Virtual Machine) already loads them into the project and hence, we can use these classes again and again. One such example is the main method. These classes/methods are already predefined for us so there is no need for us to instantiate such classes/methods because they are static.

You don't need to create object of System and Math class to use it because they have static methods . Static methods belong to the class and thus doesn't require it to be instantiated.

Although, you can create its object and then also use those methods, but creating a class for static method is of no use.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM