Inheritance Flashcards
When to use a abstract class as superclass
When a subclass definitely has an “is-a” relationship with the superclass.
Benefits of using an abstract class
Superclasses can have methods added to the subclass without changing the subclass.
Abstract classes can define attributes that are not static and not final.
Methods do not have to be public.
When to use an interface over an abstract class
When a class will use an interface or the class is a “has-a” relationship
Benefits of using an interface
Allows code to be loosely coupled with dependencies allowing different implementations of the interface to be used at runtime.
Classes can use multiple interfaces.
This allows for greater testability by swapping out mock classes.
It follows the Liskov Substitution Principle and Open/Closed Principle of SOLID
What is inheritance
A mechanism to derive a class from another class for a hierarchy of classes that share a set of attributes and methods.
What are the modifiers
Public: Can be accessed by anyone
Protected: Can only be accessed by itself, child, and friend classes
Private: Can only be accessed by itself
No Modifier: Can be accessed by itself and classes in the same package
final keyword
Ensure that a subclass does not override a method
Issues with using an abstract class over an interface
Subclasses can only inherit one class. Since subclasses are tightly-coupled to their superclass, any change to the abstract class causes changes to any other subclass inheriting from it.