Unit 3 · OOP Concepts

3.8.4Self-check and practice

Self-check questions

Write your answers first, then open the answers to check them.

  1. Why can an abstract class not be instantiated?
  2. Can an abstract class have a constructor? Why would it need one?
  3. Give two differences between an abstract class and an interface.
  4. When would you choose an interface rather than an abstract class?
Show answers
  1. It is incomplete: it may contain abstract methods with no body, so an object of it could not run them. The abstract keyword makes the compiler forbid new on the class; only its concrete subclasses can be instantiated.

  2. Yes. You cannot call it with new directly, but each subclass constructor calls it with super(...) to initialise the attributes declared in the abstract class (for example name in Employee).

  3. 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).
  4. When unrelated classes need the same capability (Bird, Aeroplane and Drone are all Flyable), when a class needs more than one type (a Duck is Flyable and Swimmable), or when you only want to define a contract with no shared code or state.

Practice exercises

  1. Create an abstract class Shape with abstract area() and perimeter(). Implement for Circle, Rectangle and Triangle.
  2. Create an interface Drawable with draw(), and Resizable with resize(double factor). Implement both in a Square class.
  3. Build a notification system: interface Notifier with send(String message); classes EmailNotifier, SmsNotifier. Write a method that sends a message through any Notifier.
  4. Explain with an example why abstraction and polymorphism are used together here.