1

In "Effective Java" book Joshua Bloch says: "It is impossible to subclass any of the convenience implementation classes in the Collection Framework".

Why does he point it if ArrayList, LinkedList, HashSet etc. have public constructors and can be easily subclassed?

Could you please also explain me why can't we extend a mutable class by an immutable one?

If an immutable class has package-private constructor and fields and can be modified by a mutable child class anyway the INSTANCE of immutable will be created only for child class and a user will not use the parent class.

4
  • 1
    He doesn't talk about LinkedList. He talks about java.util.Collections$SingletonSet and java.util.Arrays$ArrayList. Feb 9, 2018 at 17:01
  • He probably meant to say "It is impossible to subclass any of the convenience implementation classes in the Collection Framework when using factory methods" Feb 9, 2018 at 17:03
  • 2
    I also do not understand what you mean by "we cannot extend a mutable class by an immutable one". What does that mean to you? Extending mutable class and overriding all mutation methods to throw exceptions is definitely possible. Feb 9, 2018 at 17:07
  • I am asking about extending an immutable class by a mutable as I thought at first that we couldn't extend collections just because they are immutable. Feb 9, 2018 at 17:59

1 Answer 1

7

Read the broader quote:

The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed. The same is true for nonpublic classes returned by public static factories. For example, it is impossible to subclass any of the convenience implementation classes in the Collections Framework.

It's talking about things like Collections.unmodifiableList, Collections.singleton, Collections.synchronizedMap: you can't subclass the type returned by those methods.

2
  • Sorry. I can subclass the type returned by Collections.unmodifiableList. It is List Feb 9, 2018 at 17:56
  • @Pavel that's not what subclassing means. Feb 10, 2018 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.