Self-check questions
Write your answers first, then open the answers to check them.
- Why can an abstract class not be instantiated?
- Can an abstract class have a constructor? Why would it need one?
- Give two differences between an abstract class and an interface.
- When would you choose an interface rather than an abstract class?
Show answers
It is incomplete: it may contain abstract methods with no body, so an object of it could not run them. The
abstractkeyword makes the compiler forbidnewon the class; only its concrete subclasses can be instantiated.Yes. You cannot call it with
newdirectly, but each subclass constructor calls it withsuper(...)to initialise the attributes declared in the abstract class (for examplenameinEmployee).Any two:
- An abstract class can have instance attributes and constructors; an interface has only constants and no constructors.
- A class can extend only one abstract class but implement many interfaces.
- An abstract class suits closely related classes that share code (is-a); an interface suits unrelated classes that share a capability (can-do).
When unrelated classes need the same capability (Bird, Aeroplane and Drone are all
Flyable), when a class needs more than one type (a Duck isFlyableandSwimmable), or when you only want to define a contract with no shared code or state.
Practice exercises
- Create an abstract class Shape with abstract
area()andperimeter(). Implement for Circle, Rectangle and Triangle. - Create an interface Drawable with
draw(), and Resizable withresize(double factor). Implement both in a Square class. - Build a notification system: interface Notifier with
send(String message); classes EmailNotifier, SmsNotifier. Write a method that sends a message through any Notifier. - Explain with an example why abstraction and polymorphism are used together here.