W3 Flashcards
(2 cards)
1
Q
What makes a class abstract? A method?
A
An abstract class is any class that has the keyword “abstract” in its signature. Once you include that keyword, it is no longer possible for you to create an instance of that class by calling its constructor. It can therefore have abstract methods in it.
Abstract classes are meant to provide a common foundation for subclasses to build upon, and they can include abstract methods (methods without implementations) as well as concrete methods (methods with implementations).
2
Q
How can we decide whether we should use an interface or an abstract class?
A
-
Use an interface if:
- You need multiple inheritance of behavior (a class should have multiple capabilities).
- You are designing a flexible API where unrelated classes can implement a common set of behaviors.
- You need to specify behavior that must be implemented across various, possibly unrelated classes.
-
Use an abstract class if:
- You have shared code, shared fields, or default behavior that should be inherited by all subclasses.
- You want to force subclasses to implement certain methods while providing some default behavior.
- You need constructors to initialize common fields.
- There is a strong hierarchical relationship between classes, with shared state and behavior.