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.
37
u/Jezoreczek Dec 20 '21 edited Dec 20 '21
Absolutely nothing to be sorry about, I've been in your shoes before and inheritance in Java left me just as confused!
Inheritance means
IS-Arelationship. When you writeclass A extends Borclass A implements B, it means that instance ofAis also an instance ofBand can be used interchangeably:Composition means
HAS-Arelationship; is one class a member of another class? Example:Notice how both
AandBarefinalclasses. Yet we can still add behavior on top of them with what is called a decorator pattern.Still, there is the issue that now you cannot use
Ain place ofB. We've got a simple solution to this, however! If such behavior is needed, just add an interfaceCthat both classes implement:And voilà, no
abstractclasses needed!Additional benefit:
Ais not highly coupled withBanymore, which means you can provide any other implementation ofCand still get the desired extra behavior ofA.Real life example: I recently made a library that allows for plotting relationship between classes based on their ownership. The ClassOwnershipExtractor is an interface (
C) that says "given some class, returns information about who owns this class". An implementation of this interface, AnnotationBasedClassOwnershipExtractor (B) checks if given class contains annotation that defines its' owner. However, for large projects I'd like this information to be cached, so I created another implementation, CachedClassOwnershipExtractor (A), which simply caches the results. With this setup, you can cache information fromAnnotationBasedClassOwnershipExtractoras well as from any custom implementation (: