I am working on the development of an SDK in Android with Java, In general the user doesn't need to inherit any class of the SDK, so the question is if it is a good practice put by default all classes as final in the SDK's Classes?


In general, unless you're specifically designing your classes to be inheritable, it's better to mark them final.

Here's why: you can't predict how someone might use your class. If you allow inheritance, your clients may use them (or break them) in unexpected ways. If you don't design the class specifically to be inherited, you may break their code when you update your classes.

Leaving classes unsealed means that someone who inherits the class has access to its internals. Effectively, these internals become part of your public API. So if you want to control your API surface, the class must be final.

Eric Lippert provides a detailed treatment of the subject here.

  • 1
    Also, you can always make them virtual later. You can't make them final. Oct 10 '19 at 15:46
  • My be worth adding that declaring classes final allows more scope to change those classes in future versions of the SDK while keeping backward compatibility. For instance a final class can freely have its method return types narrowed.
    – bdsl
    Oct 10 '19 at 17:00
  • I'm quite sure that clients can break your class (o.k., maybe not your class, but certainly mine :-)) even if it is final. And I'm sure that I can break their code on an update even if it is final. That's what semantic versioning is for.
    – user949300
    Oct 10 '19 at 17:38

If another developer can change your class from final to non-final then marking it as final doesn’t mean “cannot be subclassed”, it means “I didn’t give the question whether it can or should be subclassed one second thought, if you subclass it then it is completely your responsibility”.

If that is the case, make it final.

If other developers cannot modify your class then final does prevent subclassing. Only make it final if subclassing must be prevented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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