views:

85

answers:

3

I'm becoming more interested in API's and was about starting to write my own, but then I was thinking a bit about the standard library of Java.

The standard library of Java has a String class with tons of methods, isn't this bad design? I mean, if I would create a new instance of the String class, it would create an object with dozens of methods (toUpper, toLower, etc.); wouldn't this take up much memory for such a simple string?

Thanks,

William van Doorn

+12  A: 

No - you only "pay" for methods once, not once per instance. After all, the code doesn't change for each different instance of String, so why would you want a new copy of it for each instance?

(In some prototype based languages I suspect there may be penalties for objects with lots of methods, depending on how they're assigned... but you'd have to ask about very specific situations.)

While the String class in Java does have a lot of methods, the same situation occurs in many platforms - because there are so many ways you can use a string.

Jon Skeet
Even prototype-based languages usually don't have multiple copies of the same method floating around. Objects normally share the methods of their parents.
Chuck
@Chuck: Presumably it would depend on whether the methods had been inherited or individually assigned though. That sort of consideration is precisely why I said you'd have to talk about specific situations :)
Jon Skeet
Thanks, very elegant and complete answer. Marked as accepted.
wvd
+6  A: 

Methods don't take up memory per object. You can think of a.myMethod() as syntactic sugar for myMethod(a). (Of course, there's more going on behind the scenes, but this might help you understand why a whole lot of methods does not mean that object creation needs a lot of memory.)

Heinzi
+1  A: 

Methods don't add to objects memory space.

That is until they are called. Then some memory will be taken for the new stack frame and released back after the method is through.

Developer Art