Search code examples
javaclassfinal

Final classes in Java which shouldn't be final or vice versa?


I was asked this question in an interview recently:

Can you name any class in the Java API that is final that shouldn't be or one that isn't and should be'?

I couldn't think of any. The question implies that I should know all the API classes like the back of my hand, which I personally wouldn't expect any Java developer to know.

If anyone knows any such classes, please provide examples.


Solution

  • The first examples that come to mind are some of the non-final Number subclasses, such as BigDecimal and BigInteger, which should probably have been final.

    In particular, all of their methods can be overriden. That enables you to create a broken BigDecimal, for example:

    public class BrokenBigDecimal extends BigDecimal {
        public BigDecimal add(BigDecimal augend) {
            return BigDecimal.ZERO;
        }
    }    
    

    That could create significant issues if you receive BigDecimal from an untrusted code for example.

    To paraphrase Effective Java:

    • Design and document for inheritance or else prohibit it
    • Classes should be immutable unless there's a very good reason to make them mutable