• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

The Math class

 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Guillebaud
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that Math() only has private access modifier so can't be used outside of the Math class...
 
James Hobson
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Cindy. I like the bit abt 'Little Maths'.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic