Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with Math class without instantiating it

Tags:

java

oop

I am new to programming and was studying "Head First Java", I just saw a problem where there was used Math class like this

int x= Math.round(float value);

and it was mentioned we don't need to instantiate Math class because its constructor is set private. What does that mean? Until now I read we need to instantiate that class and reference variable to play around with methods and instance variables of the class how does Math class work like this?


1 Answers

we don't need to instantiate Math class because its Constructor is set Private

Because all the methods in Math class are static you can use the class name to invoke them. So there is no use instantiating the class , hence the constructor was declared private. it will also prevent sub classing the Math class, since it is the only constructor.

Look at the open source code :

Don't let anyone instantiate this class.

 private Math() {} // only constructor defined in Math class

The methods of Math class doesn't depend on the internal state of the class , they are just like utility functions . So it was wise to declare them as static. static methods can be invoked by directly using the classname , hence no use of instantiating the class. They belong to the class, not specific objects of that class.

You can refer the JLS 8.4.3.2 :

A class method is always invoked without reference to a particular object.

like image 117
AllTooSir Avatar answered May 06 '26 00:05

AllTooSir