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
OK, but the original question was "Why use private constructors when you could declare the class abstract"
The answer is:
Sun (quite rightly) don't want us idiots subclassing Math and changing the functionality. That's why the Math class is declared final.
You can't declare an abstract class final. Therefore, if Math were implemented as an abstract class, it could be subclassed.
So... it's not just a random choice between the two methods. By using the private constructors technique you can stop people both instantiating and subclassing Math. Yippe kay aye!
Sadashiv Borkar
Ranch Hand
Joined: Jun 07, 2000
Posts: 49
posted
0
Hi Dave, Thanx for the answer it was really a nice one which cleared my doubts. bye take care sada