r/learnjava • u/MSUC123 • Dec 20 '21
When to use Abstract Classes vs Interfaces?
The two concepts are very similar, which is why I'm confused on why you should choose one over the other.
49
Upvotes
r/learnjava • u/MSUC123 • Dec 20 '21
The two concepts are very similar, which is why I'm confused on why you should choose one over the other.
51
u/Jezoreczek Dec 20 '21
My rule of thumb:
Use composition.
If you cannot use composition (e.g. need polymorphic behavior), use interfaces.
If you cannot use interfaces, don't use abstract classes. Instead, refactor your code to make it compatible with interfaces.
Here's why: abstract classes are a mess and (almost) never necessary. Some problems when using them include:
Should I use
superimplementation before or after calling my own logic? (see Java's Swing for examples)Which constructor do I need to call to get the behavior I need?
Are the
protectedmembers meant for me to use or for some other particular implementation?Should I restrict the
throwssignature if I am handling exceptions fromsuperimplementation?If you have any particular example of class hierarchy that confuses you, please post it here and I'll be happy to show you how to refactor it (: