Chapter 4.5: Abstract Classes and Interfaces

Chapter 4.5: Abstract Classes and Interfaces · Study Questions
AbstractionAbstract class and methodTemplate methodInterfaces and implementsLambda expressionsdefault / static / privateSealed typesInterface or abstract class?
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Abstraction

Question 1: The Purpose of Abstraction

What do abstract classes and interfaces in Java have in common?

B: Both are tools of abstraction: they define the “what” (method signatures, the contract) at the top and leave the “how” to the subclasses or implementing classes. Classes have no multiple inheritance (A); neither can be instantiated with new (C); calls are still bound dynamically (D).

Multiple Choice · Abstract Classes

Question 2: Which One Compiles?

Which of the following one-line definitions compiles?

C: An abstract class with no abstract methods is valid (though new A() still cannot be written). A: abstract methods cannot have a body. B and D: illegal combination of modifiers; private and final prevent overriding, while abstract methods and abstract classes exist for subclasses.

Spot the Bug · Abstract Classes

Question 3: Area() ≠ area()

Which lines give a compile error? How is each one fixed?

abstract class Shape {
  String name;
  Shape(String name) { this.name = name; }
  abstract double area();
}
class Square extends Shape {
  double k;
  Square(double k) { super("Square"); this.k = k; }
  double Area() { return k * k; }
}
// in main:
Shape s = new Shape("?");
Shape[] d = new Shape[2];
Show answer
  • class Square: Square is not abstract and does not override abstract method area() in Shape. Area() (capital A) is a new method; the abstract area() is still missing. The name must be fixed; if @Override is written on it, such typos are caught immediately.
  • new Shape("?"): Shape is abstract; cannot be instantiated. A concrete subclass is used: Shape s = new Square(3);
  • new Shape[2] compiles: it creates not Shape objects but two empty (null) references. An abstract class having a constructor is also valid.

Step-by-Step Trace · Abstract Classes

Question 4: Abstract Type, Concrete Object

The abstract class has a constructor and a concrete summary() method. What does the program print?

Shape (static)count1StackHeapShape(String)name"Square"Square(double)k2.0main()d?#1 Squarename"Square"k2.0

new Square(2): the Square constructor calls the abstract class’s constructor with super("Square"). No separate Shape object is created; the Shape part of the same object is set up. count = 1.

Shape (static)count2StackHeapmain()d[0]d[1]#1 Squarename"Square"k2.0#2 Circlename"Circle"r1.0

The second object is set up the same way (count = 2). The array’s element type is the abstract Shape; what its elements refer to are concrete objects.

Shape (static)count2StackHeapsummary()thismain()d[0]d[1]s#1 Squarename"Square"k2.0#2 Circlename"Circle"r1.0

summary() is concrete and comes from Shape. The area() inside it is abstract; this is a Square → Square.area(): 4.0.

Shape (static)count2StackHeapsummary()thismain()d[0]d[1]s#1 Squarename"Square"k2.0#2 Circlename"Circle"r1.0

Same line, different object: this time Circle.area() = 3 · 1 · 1 = 3.0. Code in the abstract class calls the method the subclass wrote.

Shape (static)count2StackHeapmain()d[0]d[1]#1 Squarename"Square"k2.0#2 Circlename"Circle"r1.0

The static counter counted the two constructor calls: 2.

abstract class Shape {
  static int count = 0;
  String name;
  Shape(String name) { this.name = name; count++; }
  abstract double area();
  String summary() { return name + ":" + area(); }
}
class Square extends Shape {
  double k;
  Square(double k) { super("Square"); this.k = k; }
  double area() { return k * k; }
}
class Circle extends Shape {
  double r;
  Circle(double r) { super("Circle"); this.r = r; }
  double area() { return 3 * r * r; }
}
// in main:
Shape[] d = { new Square(2), new Circle(1) };
for (Shape s : d) System.out.println(s.summary());
System.out.println(Shape.count);

Output Question · Abstract Classes

Question 5: Tea or Coffee?

What does the program print? What happens if someone tries to override the final prepare() in Tea?

abstract class Beverage {
  final void prepare() {
    System.out.print("water ");
    brew();
    if (milk()) System.out.print("milk ");
    System.out.println("serve");
  }
  abstract void brew();
  boolean milk() { return false; }
}
class Tea extends Beverage {
  void brew() { System.out.print("tea "); }
}
class Coffee extends Beverage {
  void brew() { System.out.print("coffee "); }
  @Override boolean milk() { return true; }
}
// main: new Tea().prepare();
//       Beverage i = new Coffee(); i.prepare();
Show answer
water tea serve
water coffee milk serve
  • The skeleton (the order) is in the abstract class, the varying step in the subclass: a template method.
  • brew() runs in each object with its own class’s version. milk() is a “hook”: only Coffee overrides it.
  • A final method cannot be overridden: prepare() in Tea cannot override prepare() in Beverage; overridden method is final. Subclasses cannot break the order.

Multiple Choice · Interfaces

Question 6: A Field in an Interface

Which statement is true for interface GeometricShape { int SIDE_COUNT = 4; void draw(); }?

A: In an interface only constants can be defined as fields: implicitly public static final. GeometricShape.SIDE_COUNT = 5; → cannot assign a value to static final variable; giving no value → = expected. Methods without a body are implicitly public abstract (C).

Multiple Choice · Interfaces

Question 7: When public Is Forgotten

class Square implements GeometricShape { void draw() { } } is written. What happens?

D: An interface method is implicitly public; the implementing method cannot narrow access: draw() in Square cannot implement draw() in GeometricShape; attempting to assign weaker access privileges; was public. The correct form is public void draw().

Step-by-Step Trace · Interfaces

Question 8: A Basket of an Interface Type

Three unrelated classes implement the same interface. After the loop, what are total and the price of the most expensive item?

StackHeapmain()baskettotal0.0mostExpensivef?#0 Priced[][0][1][2]#1 Book#2 Pencount4#3 Ticket

The array’s element type is an interface; the elements refer to objects of three unrelated classes. All they share is the Priced contract.

StackHeapmain()baskettotal40.0mostExpensivef#0 Priced[][0][1][2]#1 Book#2 Pencount4#3 Ticket

f → Book: Book.price() = 40.0. 40 > 40 is false; the most expensive stays the same.

StackHeapmain()baskettotal70.0mostExpensivef#0 Priced[][0][1][2]#1 Book#2 Pencount4#3 Ticket

f → Pen: 7.5 × 4 = 30.0; total 70.0. 30 > 40 is false.

StackHeapmain()baskettotal95.0mostExpensivef#0 Priced[][0][1][2]#1 Book#2 Pencount4#3 Ticket

f → Ticket: 25.0; total 95.0. The same call runs a different class’s method in each round (dynamic binding).

StackHeapmain()baskettotal95.0mostExpensivef?#0 Priced[][0][1][2]#1 Book#2 Pencount4#3 Ticket

Output: 95.0 40.0. Adding a new Priced class does not change the loop.

interface Priced { double price(); }
class Book implements Priced {
  public double price() { return 40; }
}
class Pen implements Priced {
  int count;
  Pen(int count) { this.count = count; }
  public double price() { return 7.5 * count; }
}
class Ticket implements Priced {
  public double price() { return 25; }
}
// in main:
Priced[] basket = { new Book(), new Pen(4),
                    new Ticket() };
double total = 0;
Priced mostExpensive = basket[0];
for (Priced f : basket) {
  total += f.price();
  if (f.price() > mostExpensive.price()) mostExpensive = f;
}
System.out.println(total + " " + mostExpensive.price());

Output Question · Lambda Expressions

Question 9: Calculating and Filtering with Lambdas

The imports are in place. What does the program print?

IntBinaryOperator f = (a, b) -> a * b + 1;
IntUnaryOperator g = x -> x * x;
int t = f.applyAsInt(3, 4) + g.applyAsInt(5);
System.out.println(t);
List<Integer> l =
        Arrays.asList(5, 8, 3, 12, 7);
System.out.println(l.stream()
        .filter(s -> s > 5)
        .map(s -> s / 2)
        .collect(Collectors.toList()));
Show answer
38
[4, 6, 3]
  • f.applyAsInt(3, 4) = 3 · 4 + 1 = 13; g.applyAsInt(5) = 25. Both are int: 13 + 25 = 38.
  • filter keeps those that satisfy the condition: 8, 12, 7 (order is preserved). map transforms each: 8 / 2 = 4, 12 / 2 = 6, 7 / 2 = 3 (integer division).

Step-by-Step Trace · Interface Methods

Question 10: A default Method and Overriding

twice() is written once in the interface. How many increments does it make on the two objects? What does the program print?

StackHeapmain()ab#1 Simpled0#2 Doublingd0

Two objects, both held through references of type Counter. Doubling gets the field d from Simple (private, accessible only through methods).

StackHeapincrement()thistwice()thismain()ab#1 Simpled1#2 Doublingd0

twice() is the interface’s default method; Simple did not write one, so it runs. The increment() inside it = this.increment() → Simple’s version: d = 1.

StackHeapincrement()thistwice()thismain()ab#1 Simpled2#2 Doublingd0

Second call: d = 2.

StackHeapDoubling.increment()thistwice()thismain()ab#1 Simpled2#2 Doublingd2

The same default method, but this is a Doubling: the overridden increment() calls super.increment() twice → d = 2.

StackHeapDoubling.increment()thistwice()thismain()ab#1 Simpled2#2 Doublingd4

Second increment(): d = 4.

StackHeapmain()ab#1 Simpled2#2 Doublingd4

isZero() is also default: value() is 4, not zero. Output: 2 4 false.

interface Counter {
  int value();
  void increment();
  default boolean isZero() { return value() == 0; }
  default void twice() { increment(); increment(); }
}
class Simple implements Counter {
  private int d;
  public int value() { return d; }
  public void increment() { d++; }
}
class Doubling extends Simple {
  @Override public void increment() {
    super.increment(); super.increment();
  }
}
// in main:
Counter a = new Simple();
Counter b = new Doubling();
a.twice();
b.twice();
System.out.println(a.value() + " " + b.value()
    + " " + b.isZero());

Multiple Choice · Interface Methods

Question 11: A static Method of an Interface

Given interface Calc { static int sum(int a, int b) { return a + b; } } and class Simple implements Calc { }, which statement is true for Calc.sum(3, 4) and Simple.sum(3, 4)?

A: The static methods of an interface are not inherited by the implementing class; they are called only through the interface name. Simple.sum → cannot find symbol. (static methods in classes, however, can also be called through the subclass name.)

Output Question · Interface Methods

Question 12: Two default greet() Methods

Two interfaces bring a default method with the same signature. What does the program print? What would happen if greet() had not been written in Clerk?

// p(s): System.out.println(s)
interface Greeter {
  default void greet() { p("Hello"); }
}
interface Welcomer {
  default void greet() { p("Welcome"); }
}
class Clerk implements Greeter, Welcomer {
  public void greet() {
    Welcomer.super.greet();
    p("I am the clerk");
  }
}
// in main:
Greeter s = new Clerk();
s.greet();
Show answer
Welcome
I am the clerk
  • Even though the reference has type Greeter, the object is a Clerk: its greet() runs.
  • Welcomer.super.greet() calls only that interface’s default version; Hello is never printed.
  • Without greet() it would not compile: class Clerk inherits unrelated defaults for greet() from types Greeter and Welcomer.

Multiple Choice · Interface Methods

Question 13: A private Interface Method

Who can call the method private String title() { return "Document"; } in a Java 9+ interface?

C: private interface methods exist to share common helper code of default and static methods without exposing it. The implementing class Report cannot call title(): cannot find symbol.

Multiple Choice · Sealed Types

Question 14: A Sealed Hierarchy

sealed abstract class Shape permits Square, Circle; final class Square extends Shape; non-sealed class Circle extends Shape. Which statement is true? (Java 17+)

B: non-sealed lifts the restriction; anyone can extend Circle. Triangle is not in the permits list: class is not allowed to extend sealed class: Shape.

Spot the Bug · Sealed Types

Question 15: A Subtype Missing a Modifier

The code does not compile (Java 17+). On which line is the error, and what is it? Write three different fixes; what does each one mean?

sealed interface Animal permits Cat, Dog { }
class Cat implements Animal { }
final class Dog implements Animal { }
Show answer
error: sealed, non-sealed or final
  modifiers expected
class Cat implements Animal { }

Every subtype in the permits list must choose one:

  • final class Cat: the hierarchy ends here.
  • sealed class Cat permits Tabby: restricts again (Tabby must also choose one).
  • non-sealed class Cat: anyone can extend it.

Multiple Choice · Comparison

Question 16: Only in an Abstract Class

Which of the following can be done in an abstract class but cannot be done in an interface?

D: An interface has no objects or state: instance fields and constructors cannot be defined. A method with a body is possible in an interface too (default, static, private); constants can be defined in both; a class taking several types together (B) is possible only with interfaces.

Coding Question · Comparison

Question 17: Vehicle and Charging

Vehicle has a plate and a constructor, and an abstract method int wheelCount(); Chargeable has a constant CAPACITY = 100 and a method void charge(int percent). Which should be an abstract class and which an interface? Write ElectricCar, which uses both, starts at a 20% level and never exceeds the capacity. What is the level after calling charge(50) twice?

Show answer

Vehicle: a shared field + a constructor → abstract class. Chargeable: an ability that can also be given to unrelated classes → interface.

class ElectricCar extends Vehicle
    implements Chargeable {
  private int level = 20;
  ElectricCar(String plate) { super(plate); }
  int wheelCount() { return 4; }
  public void charge(int percent) {
    level = Math.min(CAPACITY, level + percent);
  }
  int getLevel() { return level; }
}

20 → 70 → 100 (not 120): 100. extends first, then implements; charge must be public. The object can be assigned to a reference of type Vehicle as well as of type Chargeable.

The End

Chapter 4.5: Abstract Classes and Interfaces: Study Questions
Lecture slides: Chapter 4.5: Abstract Classes and Interfaces · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.