Could anyone tell me what I am doing wrong right here?
private static java.lang.Math a = new java.lang.Math();
It's resulting an error, but I have no idea why.
Could anyone tell me what I am doing wrong right here?
private static java.lang.Math a = new java.lang.Math();
It's resulting an error, but I have no idea why.
You can't instantiate a Math instance. It's all static methods. There's no public default constructor.
Could anyone tell me what I am doing wrong right here?
The answer is you are trying to instantiate a class with a single private
constructor, from outside the class.
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
a.abs(int min - int max); !!
You can do the following way :
int min = xxx;
int max = yyy;
int abs = Math.abs(min-max);
You're trying to instantiate java.lang.Math... and I'm not sure why.
Just use it like this:
java.lang.Math.sin(x);
Why to create new Object,Its final class and all methods are static.
I was trying to say why to create an object if all methods are static and since it's final ,constructor call may fail
You can't (without reflection) create object of class if you don't have access to its constructor, like in this case, where constructor is private.
I already have a Math class so thats why I am trying other options
All important methods of java.lang.Math
are static so you don't need instance of that class to invoke them. Just use Math.abs(x - y)
or in your case java.lang.Math.abs(x - y)
to specify that you want to use java.lang.Math
, not your class.
In case you just want to use just few methods from java.lang.Math
you can just import them like
import static java.lang.Math.abs;
and use it like
abs(10 - 20)
You can also try this way
java.lang.Math a = null;
a.abs(x - y); // compilator will change it to
//java.lang.Math.abs(x - y) since abs is static method
but I would stay with java.lang.Math.abs(x - y)
since it is more readable.
You can not create an object of Math class because the constructor of Math class has a private modifier.
Further, all the methods in the class are static. So you can use them directly ( ex : Math.method() ). By extension, the presence of only static methods in the class does not ever necessitate object construction.
So, one cannot instantiate Math because it was designed such that no one should ever find a need to instantiate it.
You can instantiate Math, but you shouldn't, unless it is for some obscure reason.
public static void main(String[] args) throws Exception {
Constructor<?> constructor = Math.class.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Math math = (Math) constructor.newInstance();
...
}