Abstract classes

The abstract class in Java: not instantiable, abstract methods to override, shared concrete methods, a concrete or still abstract subclass, and the template method.

  • 17 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Abstract class: what is it?

    Show the answer

    A class that acts as a common model for its subclasses: no object can be created from it directly, and it may leave methods without a body.

    It gathers what is shared (attributes, concrete methods) without claiming to be a complete object. new Shape() is rejected if Shape is abstract.

  • Shape is an abstract class. What message does the compiler give for this line?

    ```java
    Shape f = new Shape();
    `

    • Shape is abstract; cannot be instantiated
    • Shape is not abstract and does not override abstract method area() in Shape
    • cannot find symbol : constructor Shape()
    • abstract methods cannot have a body
    Show the answer

    Shape is abstract; cannot be instantiated

    new on an abstract class is forbidden: the object would be incomplete. The other message, which looks alike, targets a concrete subclass that forgets an abstract method.

  • A class that contains an abstract method must itself be declared ….

    Show the answer

    A class that contains an abstract method must itself be declared abstract.

    Otherwise one could create an object with a method that has no body. The compiler answers: Shape is not abstract and does not override abstract method area() in Shape.

  • Abstract method: what is it?

    Show the answer

    A method declared without a body, which every concrete subclass is obliged to override.

    It sets the obligation without imposing the way: abstract double area(); says every shape has an area, and each shape computes its own.

  • Can a class with no abstract method be declared abstract?

    • Yes: it forbids new while keeping the shared code
    • No: abstract requires at least one abstract method
    • Yes, but only with a private constructor
    • No: the compiler rejects it with class has no abstract method
    Show the answer

    Yes: it forbids new while keeping the shared code

    The abstract keyword on a class only forbids instantiating it. The rule works one way only: an abstract method requires an abstract class, not the reverse.