简体   繁体   中英

Why using static methods is recommended in Effective Java?

I'm looking at chapter 1 of Effective Java(3th ed, Joshua J. Bloch)

and It says using a static method is better than constructor.

But I understand that static is loaded in memory when classloader initiates,

and in normal case the static members are not removed by garbage collector

until the class unloaded.

So if I understood right, when I use more and more classes which have static method,

It consumes more memory, am I right?

Is that memory timid to concern, or there are other reasons to use them nevertheless?

Static member variables are not garbage collected (assuming the classloader is still alive), since the class itself will always hold a reference to it. The same is not true of methods .

Static methods (aka factory methods) are sometimes preferred for a few reasons.

  • You can name them how you want: Imagine the following constructor: public Hyperlink(String string){...} . It is not clear what the string actually refers to. Is it the text to be made into the link? Is it the URL? Imagine instead the static factory public Hyperlink.fromURL(String string){...} . Much clearer.

  • Caching - the new keyword always creates a new object, or it throws an exception. There is no way to return an object that already exists in a cache somewhere. With a static factory, you could first check that the object does not already exist, and retrieve it if it does, and call a constructor if it doesn't.

  • Polymorphism - Consider the classes Animal and Dog extends Animal . The constructor public Animal(String species){...} always returns an Animal object. Dog dog = Animal.fromSpecies(String species); however, is valid.

There are of course reasons to use constructors, but personally, I will always go for a static factory method for anything vaguely complex.

Concerning memory usage, the cost of storing methods, except in very large projects or very constrained systems is negligible. Load time is another issue, but not one that is improved by avoiding static methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM