1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 2

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 classInterface
Instance fieldsYesNo (constants only)
ConstructorsYesNo
Multiple per classOne only (extends)Many (implements)
UseShared base state/behaviourCapability / 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

Question 1 · Tier 2, Understand

Fields declared in an interface are implicitly:

  1. protected
  2. public static final
  3. private
  4. non-static
Show the answer

B. Interface fields are constants, so assigning one fails to compile.

Question 2 · Tier 3, Apply

A class implements X1 and Y1, which both define default void hi(). The class does not override hi(). Result?

  1. Both versions run
  2. The first interface's version is used silently
  3. Compile-time error
  4. The code runs but prints nothing
Show the answer

C. The compiler reports that the class inherits unrelated defaults.