The class java.lang.Long has a constructor which takes in a String. It throws the NumberFormatException if the String can not parsed into a Long. It also has a static method 'valueOf' which takes in a String, returns an object of type Long, and throws NumberFormatException if it can not. I want to know the reason behind this duplication. We could've very easily lived with just one of these methods, avoiding all the redundancy and the possible confusion. Is there any profound principle of OODesign behind this?
Manfred Leonhardt
Ranch Hand
Joined: Jan 09, 2001
Posts: 1492
posted
0
Asuthosh, Hey your right! All the stinking wrapper classes have the duplication! Losing sleep ... Related Topic: Why do tire companies come out with so many tire sizes. We could've very easily live with just one size. Does this violate any OODesigns? My head hurts ....
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
0
The constructor only works if you are constructing an instance of Long. This is nice because when we are making a Long, we get the built in edit. Since the valueOf method is a static method, it can be invoked without ever creating an actual instance of Long. This is nice if we just need to edit a string without converting it into a Long or making a Long.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Asuthosh Borikar
Ranch Hand
Joined: Sep 29, 2000
Posts: 75
posted
0
Hi Cindy, Thanks for your reply. But, I think both the constructor and the static method are serving the same purpose here - returning a Long object. And the static method will also be creating a new Long object, without doing this, it can not return a Long object. So, I don't see the difference between these two methods. To illustrate, String S = "4323423423" Long L1 = new Long(S); Long L2 = Long.valueOf(S); These two lines look the same to me, and I really don't care whether I am using a constructor or a static method, as long as I get a Long from a String. So, why I have two methods? Manfred, I fail to see the analogy of this question with your 'tires' question. At the risk of being labelled a person with no sense of humor, I have to ask you to please be more elaborate in your postings. -Asuthosh.
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
0
The L1 example is the example of the constructor. However, in your L2 example you went ahead and used a constructor as well as the static method(). The point is that the valueOf static method can be used WITHOUT creating an L2 object. Long myValue = 2*Long.valueOf(S); See - No L2 object (therefore no constructor).
Matthew Jones
Ranch Hand
Joined: Dec 21, 2000
Posts: 68
posted
0
I think what Cindy was saying is that you can use the valueOf methond when you are playing with a String and you need the value, but don't want to create a new object to hold it, like this: