CAP477 · Unit 2: Object-oriented programming
Abstract classes and interfaces
8 practice questions
Key points
- Abstract class: cannot instantiate, may mix abstract and concrete members
- Interface: contract, default/static methods, constants
- A class extends one class but implements many interfaces
- Same default in two interfaces forces an override
Abstract class (abstract class Sh): cannot be instantiated; may have abstract methods (no body), concrete methods, fields and constructors (used by subclasses). A concrete subclass must implement every inherited abstract method or be abstract itself ("is not abstract and does not override abstract method"). It supports partial implementation: Sh with abstract area() and a concrete name(); new Sq(3) gives area 9.0 and name "shape".
Interface: a contract of what a class can do. Members: abstract methods (implicitly public abstract), default methods (with body, Java 8), static methods, private helper methods (Java 9), and constants (implicitly public static final, so MAX = 4 fails to compile). A class implements any number of interfaces, and implementing methods must be public (weaker access is a compile error). An interface can extend other interfaces.
Diamond conflict: if two interfaces provide the same default method, the class must override it, and can choose X1.super.hi() and Y1.super.hi() (prints X1 then Y1 above).
| Abstract class | Interface | |
|---|---|---|
| Instance fields | Yes | No (constants only) |
| Constructors | Yes | No |
| Multiple per class | One only (extends) | Many (implements) |
| Use | Shared base state/behaviour | Capability / contract |
A functional interface has exactly one abstract method (@FunctionalInterface) and can be a lambda target: Cmp c = (x, y) -> x - y; gives c.cmp(5, 3) = 2. An anonymous class implements or extends on the spot: new Ab() { void f() { ... } }.
Exam pitfall: an abstract class can have a constructor, but you still cannot call new on it directly.
Try two questions
Fields declared in an interface are implicitly:
- protected
- public static final
- private
- non-static
Show the answer
B. Interface fields are constants, so assigning one fails to compile.
A class implements X1 and Y1, which both define default void hi(). The class does not override hi(). Result?
- Both versions run
- The first interface's version is used silently
- Compile-time error
- The code runs but prints nothing
Show the answer
C. The compiler reports that the class inherits unrelated defaults.