简体   繁体   中英

Collection class has a private constructor, why not make it abstract?

public class Collections {
    // Suppresses default constructor, ensuring non-instantiability.
    private Collections() {
    }
...

All the included methods are static, if I were coding something similar I would have made the Collections.class abstract, but still have a private constructor - why is the class not defined as abstract ?

A class being abstract implies that it can (and is intended to) be extended, which is not the case with the Collections class. That's my guess.

The Collections class isn't meant to be extended or subclassed -- it's meant to just be a provider of static utility methods. If it were abstract, users could subclass it, and the JDK designers didn't want that.

You could make it

  • an abstract class
  • or an enum with no instances
  • or a final class

IMHO, It depends on what was the flavour when the class was first written, as there is littel reason to change it later.

In addition to its "technical" side (ie inability to instantiate), abstract has a semantic side facing the user of your library: it communicates an intent for others to extend the class. This is not something you are expected to do with Collections , hence marking it abstract would be a mistake.

This is a common practice, used in utility classes that only have static methods. Making the class abstract wouldn't make sense, as there are no instance methods defined. It's to prevent someone from creating an instance where it's unneeded.

List<String> myList = Arrays.asList("b", "c", "a");
new Collections().sort(myList);

where

List<String> myList = Arrays.asList("b", "c", "a");
Collections.sort(myList); 

is the "correct" way of using the utility class.

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