Hi All, While going to JLS I found out that the java.lang.Math class is having a constructor that is a private one thats the reason we r unable to create a object of Math class. Can anyone please clarify what is the reason for declaring the constructor as a private one when there is no function available with the help of which i can create an object.Why can't the class be an abstract class.Whats the advantage of declaring the constructor as a private against declaring the class as an abstract. Thanx in Advance Sada
The Math class isn't abstract because it contains a bunch of static methods. An abstract class would define only abstract methods, but they would all have to be overridden in subclasses or classes that implement the abstract class. Math's static methods contain code, and so the class its self can't be abstract.
The developers of the Math class did not want you to ever create an instance of Math. When you think about it - what is a MATH??? Therefore they made the constructor private. What they do want you to do is to use the methods of the math class without making an instance. That is why all of the methods are static (don't need an instance to use the methods)
"JavaRanch, where the deer and the Certified play" - David O'Meara
Originally posted by Nick Riviera: An abstract class would define only abstract methods, but they would all have to be overridden in subclasses or classes that implement the abstract class. Math's static methods contain code, and so the class its self can't be abstract.
First: the abstract keywords tells you, that you can't instantiate this class. That's all. You can have methods which are NOT abstract, and you won't get a compile error. Second: Of course you can have static methods in an abstract class. No compiler will prevent you to do that... See the following code for clarification
Hope that clarifies the concept of abstract classes cheers Oliver