• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

class Math is concrete class but still it cannot be instantiated.

 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was trying Math m = new Math(); and later found that Math constructor is private and it does not have any other constructors as well. I understand that all the methods in Math are static but i was just trying my SCJP knowledge.
Here is the code of class Math taken from Sun Java 1.5



In real world if requirement is to write a Utility class that has only static methods then is the above behavior of making the constructor private done just to avoid instantiation of the class inorder to save memory? Or is there any other significance behind this?

Thanks
Deepak
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Making the constructor private is a common trick for utility classes that contain only static methods and that should not be instantiated or subclassed.

Note that making the constructor private also makes it impossible to make a subclass, because the constructor of the subclass needs to be able to access the constructor of the superclass, and it can't if the constructor of the superclass is private.

I wouldn't say this is just "to save memory". Utility classes such as Math are not supposed to be instantiated. Calling static methods via an instance reference is bad style. Making it impossible to instantiate a class prevents users from using that bad style.
 
Joshua Fix
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not make the class abstract? What is the difference between an abstract class and a class with a private constructor?
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Making the class abstract still allows someone to extend the class and then instantiate that subclass. A private constructor prevents instantiation of both the class itself and any subclasses.

But note that Math is also declared to be final, to prevent it from being subclassed at all. Unfortunately, you can't declare a class as both final and abstract at the same time, so it still needs to define the private constructor to prevent instantiation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic