+ 2

Math class instantiation

Why we can not instantiate Math class in java?

19th Jun 2018, 3:22 PM
Santosh Teurwadkar
Santosh Teurwadkar - avatar
9 Respostas
+ 5
Santosh Teurwadkar http://developer.classpath.org/doc/java/lang/Math-source.html In the source code we have a private constructor declared. When we say static class we usually (but don't always) mean that all the public methods are static, meaning that there is no instance logic in the class. We only ever interact with the class in a static way.
19th Jun 2018, 7:16 PM
Dan Walker
Dan Walker - avatar
+ 7
Santosh Teurwadkar its constructor is private so its implicit( non instantiable ) it looks like this > private Math(){} followed by all its static methods so you cant create an object of that class
19th Jun 2018, 4:37 PM
D_Stark
D_Stark - avatar
+ 5
Theres no need to create a object of math class becuase its methods are static which means you can access the directly without having to create a instance of the class. The reason you cant instantiate the class is becuase its constructor is private. Just use class name and point to the static methods like so 😉 Math.sin();
19th Jun 2018, 3:58 PM
D_Stark
D_Stark - avatar
+ 1
Because you wouldn't need a Math Object. The important stuff are it's functions, which are declared static.
19th Jun 2018, 3:55 PM
Jonas Schröter
Jonas Schröter - avatar
+ 1
I'm pretty sure the Math class is static, so you can't instantiate an object of it, just like with abstract classes and interfaces. It's just there to group related methods and objects.
19th Jun 2018, 5:03 PM
LunarCoffee
LunarCoffee - avatar
+ 1
Thank you Dan, source code clears my doubt.
20th Jun 2018, 3:54 AM
Santosh Teurwadkar
Santosh Teurwadkar - avatar
0
Yes I am very much clear that all the methods and fields in Math class are static. But there is no explicit private constructor specified in math class, so implicit constructor should allow us to create an object. Is there something a I am missing?
19th Jun 2018, 4:24 PM
Santosh Teurwadkar
Santosh Teurwadkar - avatar
0
Yes D_Stark but nothing is mentioned in API documentation. I did checked on https://docs.oracle.com/javase/7/docs/api/java/lang/Math.htmI I guess I am missing or not able to something.
19th Jun 2018, 4:45 PM
Santosh Teurwadkar
Santosh Teurwadkar - avatar
0
please go through the documentation once, static keyword is not there in class declaration, only public and final are mentioned
19th Jun 2018, 6:39 PM
Santosh Teurwadkar
Santosh Teurwadkar - avatar