Hi All. Another nitty-gritty question. The java.lang.Math class is declared as public and final. It also does not contain any constructors and contains only static methods. I understand that these mathods cannot be overridden because the Math class cannot be extended by any class whatsoever. However, what's stopping the class from being instantiated? When I tested it out, the compiler complained abt the Math() constructor method not being found. Doesn't the javac provide a default constructor for classes without constructors? Hmmmmm. Please help. Thanks.
Almost correct in ever respect. The reason you cant instantiate Math is because javac provides a default constructor (no args) *only* when there are no constructors for the class. You can easily prevent instantiation by, for example creating a private constructor (this is normall for singletons). James
Joined: Aug 01, 2001
Ohhhhh.... Now I see it. Java has a hidden private Math constructor and this disables the JVM from creating the default constructor and hence disrupting the instantiation process. Thank you to the both of you.
The Math class is final so that it can not be extended. It has a private constructor so that there won't be any little Maths running around. The methods are all static so that they can be used without creating an instance of Math. Istead use the Math.method() syntax.
"JavaRanch, where the deer and the Certified play" - David O'Meara