Chapter 4.5: Abstract Classes and Interfaces

Object Oriented Programming with Java
AbstractionAbstract classesAbstract methodsInterfaces implements and multiple interfacesdefault, static, private methodsLambdas and functional interfacessealed, non-sealed, permitsInterface or abstract class?Design patterns
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Abstract class

Declare abstract classes and methods; explain why an abstract class cannot be instantiated and what a subclass must implement.

Template method

Trace code to show a concrete method of an abstract class calling an abstract method implemented in a subclass.

Interface

Declare an interface, implement one or more interfaces with implements, and use default, static and private methods.

Lambda

Recognize a functional interface; write single-method behavior as a lambda expression and trace when the lambda runs.

Design patterns

Explain which problem Singleton, Factory, Observer, Strategy and MVC solve and how they rely on interfaces.

Design decision

Recognize sealed types; decide whether a problem calls for an interface, an abstract class, or both; use generic types and annotations.

Abstraction

Abstraction

  • Abstraction: hiding complex details and showing only the essential features.
  • A driver knows the steering wheel and the pedals; they need not know what goes on inside the engine.
  • “Shape” is a concept: every shape has an area, but the area of a generic shape cannot be computed. Only Square, Circle and Triangle know their formulas.
  • Java has two tools for abstraction: abstract classes (abstract class) and interfaces (interface).
  • Both say what to do and leave how to the subclasses.
Shapehas an area, can be drawnSquarea · aCircleπ · r²Triangleb · h / 2

The common concept on top, the details below.

Abstract Classes

Abstract Class

  • Declared with the abstract keyword: public abstract class Shape.
  • May contain both abstract (bodiless) and concrete (with a body) methods.
public abstract class Shape {
    // concrete (non-abstract) method
    void move(int x, int y) {
        System.out.println("Moved to (" + x + ", " + y + ")");
    }
    // abstract method (subclasses must implement)
    abstract void draw();
}
Concrete method: move

Its body is ready. Subclasses inherit it as is, or override it if they want.

Abstract method: draw

It has only a signature. Every concrete subclass must write its own draw() body.

An abstract class is like an unfinished floor plan: some rooms are done, others only have their place marked.

Abstract Classes

Properties of an Abstract Class

  • An abstract class cannot be instantiated (it has no instances).
  • Other classes extend it with extends (inheritance).
  • A concrete subclass must implement every abstract method.
  • It gathers shared state (fields) and behavior in one place → code is reused.
  • Subclasses fill in the abstract methods to suit their needs.
  • It can have constructors; a subclass calls them with super(...).
«abstract»Shape- name : String+ Shape(name)+ getName() : String+ area() : double+ draw()Square- side+ area(): doubleCircle- r+ area(): doubleRectangle- width- height+ area(): double

In UML, abstract classes and abstract methods are written in italics.

Abstract Classes

An Abstract Class Cannot Be Instantiated

Shape s1 = new Shape("?");     // ERROR
Shape s2 = new Square(3);        // OK: abstract variable type
Shape[] arr = new Shape[3];   // OK: the array holds only references

Compiler message (line 1)

error: Shape is abstract; cannot be instantiated
Why forbidden?

Shape’s area() has no body. If new Shape() were allowed, the call s1.area() would have no code to run.

Fine as a reference type

Variables, parameters, array elements and return types can be Shape. new Shape[3] creates 3 empty (null) references, not Shape objects.

You cannot write abstract final class: final forbids extension, abstract requires it → illegal combination of modifiers: abstract and final.

Abstract Classes

Abstract Methods

  • Declared without an implementation.
  • No braces; ends with a semicolon:
public abstract void draw();
  • A class with an abstract method must itself be abstract.
  • Abstract classes usually sit at the top of an inheritance hierarchy.
public abstract class Shape {
    // abstract method
    public abstract void draw();
}

// in a separate file:
public class Circle extends Shape {
    // must implement draw
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

Output of new Circle().draw();

Drawing a circle

Abstract Classes

Rules for Abstract Methods

CodeResult
abstract void draw(); (in an abstract class)✓ OK
abstract void draw() { }abstract methods cannot have a body
class Shape { abstract void draw(); }Shape is not abstract and does not override abstract method draw() in Shape
class Circle extends Shape { } (no draw)Circle is not abstract and does not override abstract method draw() in Shape
private abstract, static abstract, final abstractillegal combination of modifiers: abstract and private (same for static, final)
abstract class Circle extends Shape { }✓ OK: an abstract subclass may leave the implementation to its own subclasses
abstract class A { void f() { } }✓ OK: an abstract class need not have any abstract methods (still, new A() is not allowed)

Why not private/static/final? All three prevent overriding in a subclass, and an abstract method exists to be overridden.

Abstract Classes · Step-by-step code trace

new Square(3): The Constructor Chain

StackHeapmains ?Square objectfrom Shapename = nullSquare’s ownside = 0.0

new Square(3): first a Square object is allocated on the heap. Fields get default values: null and 0.0.

StackHeapmains ?Square objectfrom Shapename = nullSquare’s ownside = 0.0

Square’s constructor runs. The parameter is side = 3.0 (the int 3 widened to double).

StackHeapmains ?Square objectfrom Shapename = nullSquare’s ownside = 0.0

The first step is super("Square"): the superclass constructor is called. An abstract class can have a constructor too.

StackHeapmains ?Square objectfrom Shapename = nullSquare’s ownside = 0.0

The Shape constructor runs. No separate Shape object is created: the Shape part of the same object is being built.

StackHeapmains ?Square objectfrom Shapename = "Square"Square’s ownside = 0.0

this.name = name: the object’s name field becomes "Square".

StackHeapmains ?Square objectfrom Shapename = "Square"Square’s ownside = 0.0

The message is printed. The Shape constructor ends and its frame leaves the stack.

StackHeapmains ?Square objectfrom Shapename = "Square"Square’s ownside = 3.0

Back in Square’s constructor: this.side = 3.0. The object is now fully built.

StackHeapmains •Square objectfrom Shapename = "Square"Square’s ownside = 3.0

The object’s reference is stored in s. The variable’s type is Shape (abstract); the object it points to is a Square.

StackHeapmains •Square objectfrom Shapename = "Square"Square’s ownside = 3.0

s.area(): area() is abstract in Shape. At run time the object’s type decides → Square.area(): 3.0 · 3.0.

StackHeapmains •Square objectfrom Shapename = "Square"Square’s ownside = 3.0

The returned 9.0 is printed.

abstract class Shape {
    private String name;
    Shape(String name) {
        this.name = name;
        System.out.println(name + " created");
    }
    abstract double area();
}
class Square extends Shape {
    private double side;
    Square(double side) {
        super("Square");
        this.side = side;
    }
    double area() { return side * side; }
}
// in main:
Shape s = new Square(3);
System.out.println(s.area());

Abstract Classes · Step-by-step code trace

A Concrete Method Calls an Abstract Method

«abstract»Beverage+ prepare() {final}+ boilWater()+ brew()Tea+ brew()

The variable type is Beverage (abstract), the object a Tea. Tea is concrete because it implements the only abstract method, brew().

«abstract»Beverage+ prepare() {final}+ boilWater()+ brew()Tea+ brew()

Tea has no prepare() → the concrete method inherited from Beverage runs. final: subclasses cannot change this order.

«abstract»Beverage+ prepare() {final}+ boilWater()+ brew()Tea+ brew()

Step 1: boilWater(), that is this.boilWater(), is called.

«abstract»Beverage+ prepare() {final}+ boilWater()+ brew()Tea+ brew()

The concrete boilWater() in Beverage runs.

«abstract»Beverage+ prepare() {final}+ boilWater()+ brew()Tea+ brew()

Step 2: brew(). It has no body in Beverage, but this is a Tea object…

«abstract»Beverage+ prepare() {final}+ boilWater()+ brew()Tea+ brew()

…so Tea.brew() runs. Code in the abstract class can call subclass code that has not even been written yet.

«abstract»Beverage+ prepare() {final}+ boilWater()+ brew()Tea+ brew()

Step 3: the serving message is printed.

«abstract»Beverage+ prepare() {final}+ boilWater()+ brew()Tea+ brew()

The skeleton lives in the abstract class, the varying step in the subclass: the template method pattern. A Coffee class writes only brew().

abstract class Beverage {
    final void prepare() {
        boilWater();
        brew();
        System.out.println("Served");
    }
    void boilWater() {
        System.out.println("Water boiled");
    }
    abstract void brew();
}
class Tea extends Beverage {
    void brew() {
        System.out.println("Tea brewed");
    }
}
// in main:
Beverage i = new Tea();
i.prepare();

Interfaces

What Is an Interface?

  • A contract guaranteeing that a system provides certain operations.
  • It is the integration point between two systems: the client knows only the interface.
  • Declared with the interface keyword.
  • Interface methods are public, whether or not you write public.
  • Unless it is static, default or private, a method is implicitly abstract.
  • The only fields allowed are public static final constants.
Analogy: socket and plug

A wall socket is a contract: whatever you plug in gets the same voltage. An iron and a computer both follow the socket standard; the grid knows nothing about the device’s insides, and vice versa.

An abstract class sets up an “is a kind of” (is-a) relationship; an interface defines a “can do” capability.
client codeknows«interface»GeometricShapevoid draw()SquareCircleimplements

Interfaces

Declaring an Interface

What we write

public interface GeometricShape {
    // abstract (public abstract)
    void draw();
    // constant (public static final)
    int SIDES = 4;
}

What the compiler sees

public interface GeometricShape {
    public abstract void draw();
    public static final int SIDES = 4;
}
  • Constants are accessed through the interface name: GeometricShape.SIDES → 4. Their names are written in UPPER_CASE.
  • A constant must be initialized: int value; → error: = expected.
  • A constant cannot be changed: GeometricShape.SIDES = 5; → error: cannot assign a value to static final variable SIDES.
  • An interface cannot be instantiated either: new GeometricShape() → error: GeometricShape is abstract; cannot be instantiated.

Interfaces

Implementing an Interface (implements)

  • A class implements an interface with the implements keyword.
  • It must implement all the abstract methods of the interface, or be abstract itself.
  • Missing method: Square is not abstract and does not override abstract method draw() in GeometricShape.
  • The implementing method must be public. If you write void draw(): attempting to assign weaker access privileges; was public.
  • A variable of an interface type can point to an object of any class that implements it.
public class Square implements GeometricShape {
    // must implement draw
    public void draw() {
        System.out.println("Drawing a square");
    }
}
// in main:
GeometricShape g = new Square();
g.draw();
System.out.println(GeometricShape.SIDES);

Output

Drawing a square
4

Interfaces

One Class, Several Interfaces

  • A class can extend at most one superclass (extends)…
  • …but can implement zero or more interfaces (implements A, B, …).
  • extends comes first, then implements.
  • class C extends A, B → error: '{' expected.
Animal~ name : String~ Animal(name)«interface»Flyable+ fly()«interface»Swimmable+ swim()Duck~ Duck(name)+ fly()+ swim()
class Animal {
    String name;
    Animal(String name) { this.name = name; }
}
interface Flyable { void fly(); }
interface Swimmable { void swim(); }
class Duck extends Animal implements Flyable, Swimmable {
    Duck(String name) { super(name); }
    public void fly() { System.out.println(name + " is flying"); }
    public void swim() { System.out.println(name + " is swimming"); }
}

Interfaces · Step-by-step code trace

One Object, Different Interface References

Stack: mainHeapDuck o•Flyable u—Swimmable y—Duck objectname = "Donald"fly()swim()

One Duck object is created on the heap; o points to it.

Stack: mainHeapDuck o•Flyable u•Swimmable y—Duck objectname = "Donald"fly()swim()

Assignment does not copy the object: u points to the same object. A Duck is a Flyable → the conversion is automatic.

Stack: mainHeapDuck o•Flyable u•Swimmable y•Duck objectname = "Donald"fly()swim()

y points to the same object too. One object, viewed through three different types.

Stack: mainHeapDuck o•Flyable u•Swimmable y•Duck objectname = "Donald"fly()swim()

u.fly(): u has type Flyable, so only fly() can be called on it. What runs is the object’s own fly().

Stack: mainHeapDuck o•Flyable u•Swimmable y•Duck objectname = "Donald"fly()swim()

y.swim(): type Swimmable knows swim().

Stack: mainHeapDuck o•Flyable u•Swimmable y•Duck objectname = "Donald"fly()swim()

Had we written u.swim(): error: cannot find symbol. The object has swim(), but the compiler looks at the reference type.

Stack: mainHeapDuck o•Flyable u•Swimmable y•Duck objectname = "Donald"fly()swim()

o has type Duck: everything is accessible, including the field name.

Stack: mainHeapDuck o•Flyable u•Swimmable y•Duck objectname = "Donald"fly()swim()

== compares references: all point to the same object → true.

Duck o = new Duck("Donald");
Flyable u = o;
Swimmable y = o;
u.fly();
y.swim();
// u.swim();   compile error!
System.out.println(o.name);
System.out.println(u == o);

Interfaces

Interface Inheritance

An interface can extend another interface with extends, or several separated by commas: interface C extends A, B.

public interface SquareShape extends GeometricShape {
    // may add methods or constants
    void special();
}
class SpecialSquare implements SquareShape {
    public void draw() {
        System.out.println("Drawing a special square");
    }
    public void special() {
        System.out.println("Diagonal: " + Math.sqrt(2));
    }
}
// in main:
SquareShape k = new SpecialSquare();
k.draw();
k.special();
GeometricShape g = k;   // parent interface type
«interface»GeometricShape+ SIDES : int = 4+ draw()«interface»SquareShape+ special()SpecialSquare+ draw()+ special()extendsimplements

Output

Drawing a special square
Diagonal: 1.4142135623730951

Interfaces

Programming to an Interface

  • Client code depends on the interface, not on a concrete class: variables, parameters and return types use the interface.
  • buy(PaymentMethod y, double total) does not know whether you pay by card or by transfer; it says y.pay(total) and the object does the rest.
  • A new payment type (Crypto) just implements the interface; buy never changes (loose coupling).
  • Testing gets easier: instead of a real bank, pass a fake class that implements the interface.
  • The Java library works the same way: List<String> l = new ArrayList<>();
buy(...)knows only this«interface»PaymentMethodpay(double)CreditCardTransferCrypto (new)

Interfaces · Step-by-step code trace

Payment Interface: Code Trace

StackHeapbuy()ytotal250.0main()CreditCard #1y: of type PaymentMethod

The parameter y has an interface type; the object passed in is a CreditCard.

StackHeapCreditCard.pay()amount250.0buy()ytotal250.0main()CreditCard #1y.pay() → CreditCard.pay()

y.pay(total) is bound dynamically: the object is a card, so CreditCard.pay() runs.

StackHeapmain()CreditCard #1

The call ends; nothing refers to the card object any more, so the garbage collector may reclaim it.

StackHeapbuy()ytotal120.0main()Transfer #2same buy, different object

The same buy, this time with a Transfer object.

StackHeapTransfer.pay()amount120.0buy()ytotal120.0main()Transfer #2y.pay() → Transfer.pay(): 120 + 5

This time the same line runs Transfer.pay(), which adds a 5 TL fee: 125.0.

StackHeapmain()two behaviors, buy unchanged

buy worked with two different classes without knowing either name; adding a new class would not change it.

interface PaymentMethod { void pay(double amount); }
class CreditCard implements PaymentMethod {
    public void pay(double amount) {
        System.out.println("Card: " + amount + " TL");
    }
}
class Transfer implements PaymentMethod {
    public void pay(double amount) {
        System.out.println("Transfer: " + (amount + 5) + " TL");
    }
}
static void buy(PaymentMethod y, double total) {
    y.pay(total);
}
buy(new CreditCard(), 250.0);   // main
buy(new Transfer(), 120.0);

Lambda Expressions

Anonymous (Lambda) Functions

  • Anonymous functions are functions without a name: they stand directly for a piece of code.
  • In Java they are called lambda expressions (Java 8+).
  • Syntax: (ParameterList) -> Expression
  • Multi-line body: (a, b) -> { ...; return ...; }
  • Parameter types are usually left out and inferred: (x, y) -> x + y. With one parameter the parentheses can go too: s -> s * 2.
(int x, int y) -> x + y parameter list separator expression (body) returns the result

An addition lambda: (int x, int y) -> x + y takes two integers and adds them. The equivalent method:

static int add(int x, int y) {
    return x + y;
}

Lambda Expressions

Functional Interfaces

  • Functional interface: an interface with exactly one abstract method. A lambda can only be assigned to such a type.
  • The lambda supplies the body of that one method; parameter and return types are inferred from the method.
  • @FunctionalInterface is optional; if present, the compiler refuses a second abstract method.
  • A lambda does not run when it is defined; it runs when the method is called (s.greet(...)).
@FunctionalInterface
interface Greeting {
    void greet(String name);
}

Greeting s = name -> System.out.println("Hello " + name);
s.greet("Ayşe");
Output
Hello Ayşe
interface Greetingvoid greet(String name);name -> System.out.println("Hello " + name)single abstract methodlambda = method body

Lambda Expressions

Built-in Functional Interfaces

You need not write an interface every time: package java.util.function provides the common shapes.

InterfaceInputOutputMethodTypical use
Consumer<T>one valuenoneacceptprinting, saving
Supplier<T>noneone valuegetproducing a value
Function<T, R>one valueone valueapplytransforming
Predicate<T>one valuebooleantestfiltering, conditions
Consumer<String> print = m -> System.out.println(m);
print.accept("Consumer ran");
Supplier<Integer> dice = () -> 4;
System.out.println(dice.get());
Function<String, Integer> len = m -> m.length();
System.out.println(len.apply("Giresun"));
Predicate<Integer> isPositive = x -> x > 0;
System.out.println(isPositive.test(-7));
Output
Consumer ran
4
7
false

Lambda Expressions · Step-by-step code trace

When Does a Lambda Run? Step by Step

isEven: x -> x % 2 == 0

The lambda is stored as a Predicate<Integer> object; its body has not run yet. isEven is a reference to that behavior.

isEven: x -> x % 2 == 0numbers38512

The list: 3, 8, 5, 12.

isEven: x -> x % 2 == 0numbers38512resultempty

The result list starts empty.

isEven: x -> x % 2 == 0numbers38512resultempty

Next element: s = 3.

isEven: x -> x % 2 == 0test(3) → falsenumbers38512resultempty

isEven.test(3) runs the lambda body: 3 % 2 == 0 → false.

isEven: x -> x % 2 == 0numbers38512resultempty

Next element: s = 8.

isEven: x -> x % 2 == 0test(8) → truenumbers38512resultempty

isEven.test(8) runs the lambda body: 8 % 2 == 0 → true.

isEven: x -> x % 2 == 0numbers38512result8

The condition holds: 8 is added to the result list.

isEven: x -> x % 2 == 0numbers38512result8

Next element: s = 5.

isEven: x -> x % 2 == 0test(5) → falsenumbers38512result8

isEven.test(5) runs the lambda body: 5 % 2 == 0 → false.

isEven: x -> x % 2 == 0numbers38512result8

Next element: s = 12.

isEven: x -> x % 2 == 0test(12) → truenumbers38512result8

isEven.test(12) runs the lambda body: 12 % 2 == 0 → true.

isEven: x -> x % 2 == 0numbers38512result812

The condition holds: 12 is added to the result list.

isEven: x -> x % 2 == 0numbers38512result812

The loop ends and [8, 12] is printed. The lambda ran four times: once per test call.

Predicate<Integer> isEven = x -> x % 2 == 0;
List<Integer> numbers = Arrays.asList(3, 8, 5, 12);
List<Integer> result = new ArrayList<>();
for (int s : numbers) {
    if (isEven.test(s)) {
        result.add(s);
    }
}
System.out.println(result);

Lambda Expressions

Lambda Example: Filtering a List

Inside main, with import java.util.*;, java.util.function.IntBinaryOperator and java.util.stream.Collectors imported:

IntBinaryOperator add = (int x, int y) -> x + y;
System.out.println(add.applyAsInt(5, 3));

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
List<Integer> evens = numbers.stream().
                    filter(s -> s % 2 == 0).
                    collect(Collectors.toList());
System.out.println(evens);
System.out.println(numbers.stream().map(s -> s * s).toList());
Output
8
[2, 4, 6]
[1, 4, 9, 16, 25, 36, 49]
  • The lambda is assigned to a functional interface type: IntBinaryOperator takes two ints and returns an int; the call is applyAsInt.
  • filter(s -> s % 2 == 0) keeps the even numbers; map transforms.
  • .toList() needs Java 16+; before that, collect(Collectors.toList()).

Lambda Expressions

Lambdas vs. Anonymous Classes

Runnable r1 = new Runnable() {
    @Override
    public void run() {
        System.out.println("Anonymous class");
    }
};
Runnable r2 =
        () -> System.out.println("Lambda");
r1.run();
r2.run();
Output
Anonymous class
Lambda

Before lambdas, single-method behavior was written as an anonymous class. A lambda does the same in one line.

Limits

  • A lambda can only be assigned to a functional interface type.
  • Local variables it uses must be final or effectively final: never reassigned afterwards.
  • Inside a lambda, this is the enclosing object; in an anonymous class it is the anonymous object itself.
int tax = 20;
Function<Integer, Integer> withTax =
        price -> price + price * tax / 100;
System.out.println(withTax.apply(150)); // 180
tax = 18;  // if added: compile error
error: local variables referenced from
  a lambda expression must be final
  or effectively final

Lambda Expressions

Where Lambdas Are Used

  • Collection operations: filtering, sorting and mapping lists (filter, sort, map, forEach).
  • Threads: concisely supplying the work to run in parallel.
  • More readable code: instead of defining a separate function for a small one-off operation.
List<String> names = new ArrayList<>(List.of("Zeynep", "Ali", "Mehmet"));
names.sort((a, b) -> a.length() - b.length());
System.out.println(names);
names.forEach(name -> System.out.println("Hello " + name));
Thread t = new Thread(() -> System.out.println("Thread ran"));
t.start();
Output
[Ali, Zeynep, Mehmet]
Hello Ali
Hello Zeynep
Hello Mehmet
Thread ran

The sort key is a lambda: a negative difference puts a first. Names of equal length (Zeynep, Mehmet) keep their original order. () -> ... is a lambda with no parameters.

Interface Methods

Default Methods (default, Java 8+)

  • An interface can have default (default) methods with a body.
  • Implementing classes inherit them and may override them. The goal: add a method to an interface without breaking the old classes that implement it.
interface Collection {
    void add(Object o);
    void remove(Object o);
    int size();
    default boolean isEmpty() {
        return size() == 0;
    }
}

Output

true
2 false
class Cart implements Collection {
    private int count = 0;
    public void add(Object o) { count++; }
    public void remove(Object o) { count--; }
    public int size() { return count; }
    // no isEmpty(): the default version is used
}
// in main:
Cart cart = new Cart();
System.out.println(cart.isEmpty());
cart.add("apple");
cart.add("cherry");
System.out.println(cart.size() + " " + cart.isEmpty());

isEmpty() calls the abstract size(); which size() runs depends on the object. (This Collection is our own interface, not java.util.Collection.)

Interface Methods · Step-by-step code trace

Default Method: Code Trace

«interface»Collectionadd(Object)size()default isEmpty()Cartadd(Object)size()Cart #1count0

Cart wrote only the two abstract methods, not isEmpty().

«interface»Collectionadd(Object)size()default isEmpty()Cartadd(Object)size()Cart #1count0no isEmpty() → default version

Lookup finds no isEmpty() in Cart, so the interface’s default body runs.

«interface»Collectionadd(Object)size()default isEmpty()Cartadd(Object)size()Cart #1count0size() → by object: Cart.size() = 0

The default method calls the abstract size(); the object decides which body runs: Cart.size() → 0.

«interface»Collectionadd(Object)size()default isEmpty()Cartadd(Object)size()Cart #1count00 == 0 → true

0 == 0: true.

«interface»Collectionadd(Object)size()default isEmpty()Cartadd(Object)size()Cart #1count1

add is Cart’s version: count becomes 1.

«interface»Collectionadd(Object)size()default isEmpty()Cartadd(Object)size()Cart #1count11 == 0 → false

The same default body now sees 1: false. A default method added after the interface was written reaches old classes without breaking them.

interface Collection {
    void add(Object o);
    int size();
    default boolean isEmpty() {
        return size() == 0;
    }
}
class Cart implements Collection {
    private int count = 0;
    public void add(Object o) { count++; }
    public int size() { return count; }
}
Collection c = new Cart();      // main
System.out.println(c.isEmpty());
c.add("apple");
System.out.println(c.isEmpty());

Interface Methods

static Methods (Java 8+)

interface Geometry {
    static double circleArea(double r) { return Math.PI * r * r; }
    static double squareArea(double s) { return s * s; }
    static double perimeter(double s) { return s * 4.0; }
    static double boxVolume(double w, double h, double d) {
        return w * h * d;
    }
}
// in main:
System.out.println(Geometry.circleArea(2));
System.out.println(Geometry.squareArea(3));
System.out.println(Geometry.perimeter(2.5));
System.out.println(Geometry.boxVolume(2, 3, 4));

Output

12.566370614359172
9.0
10.0
24.0
  • Helper functions not tied to an object; called only through the interface name: Geometry.circleArea(2).
  • They are not inherited by implementing classes: even with Circle implements Geometry, Circle.squareArea(2) → cannot find symbol.
  • A bare PI gives cannot find symbol; the constant lives in Math: Math.PI.

Interface Methods

Default Method Conflicts

  • If two interfaces bring default methods with the same signature, the class cannot tell which to take; it must write the method itself (override it).
  • A particular interface’s version can be called with InterfaceName.super.method().
interface Greeter {
    default void greet() { System.out.println("Hello"); }
}
interface Welcomer {
    default void greet() { System.out.println("Welcome"); }
}
class Clerk implements Greeter, Welcomer {
    public void greet() {       // must override
        Greeter.super.greet();
        Welcomer.super.greet();
    }
}

new Clerk().greet();

Hello
Welcome

Without greet()

error: types Greeter and Welcomer are incompatible;
  class Clerk inherits unrelated defaults for greet()
  from types Greeter and Welcomer

Interface Methods · Step-by-step code trace

Default Conflict: Code Trace

«interface»Printerwork()«interface»Scannerwork()OfficeMachinework()conflict → the class writes it itself

Both interfaces bring a default body for work(). To resolve the ambiguity, OfficeMachine writes the method itself.

«interface»Printerwork()«interface»Scannerwork()OfficeMachinework()

The reference type is Printer, but the object is an OfficeMachine: the class’s own work() runs.

«interface»Printerwork()«interface»Scannerwork()OfficeMachinework()Scanner.super.work()

Scanner.super.work(): calls the default body of the named interface.

«interface»Printerwork()«interface»Scannerwork()OfficeMachinework()Printer.super.work()

Then Printer’s. The class chooses which versions to use and in what order.

«interface»Printerwork()«interface»Scannerwork()OfficeMachinework()

Finally the class adds its own step: behavior that combines both capabilities.

«interface»Printerwork()«interface»Scannerwork()OfficeMachinework()without work(): compile error

Had OfficeMachine not written work(), the class would not compile: inherits unrelated defaults.

interface Printer {
    default void work() { System.out.println("Printing"); }
}
interface Scanner {
    default void work() { System.out.println("Scanning"); }
}
class OfficeMachine implements Printer, Scanner {
    public void work() {
        Scanner.super.work();
        Printer.super.work();
        System.out.println("Copy ready");
    }
}
Printer y = new OfficeMachine();   // main
y.work();

Interface Methods

Private Interface Methods (Java 9+)

interface Printable {
    String content();
    default void print() {
        System.out.println(title() + ": " + content());
    }
    private String title() {   // Java 9+
        return "Document";
    }
}
class Report implements Printable {
    public String content() { return "Midterm results"; }
}

new Report().print();

Document: Midterm results
  • private methods let default (and static) methods share common helper code without exposing it.
  • They have bodies and can be called only from inside the interface.
  • Implementing classes cannot see them: title() cannot be called inside Report.
  • Flow: print() (default) → title() (private) + content() (the abstract method Report implements).
print()defaulttitle()private: interface onlycontent()Report implements"Document: Midterm results"

Interface Methods

Interface Members: Summary

MemberExampleImplicit modifiersBodyJava
Abstract methodvoid draw();public abstractnone1.0
Constantint SIDES = 4;public static final—1.0
Default methoddefault boolean isEmpty() {…}publicyes8
static methodstatic double squareArea(…) {…}publicyes8
Private methodprivate String title() {…}inside the interface onlyyes9
Instance field, constructor—Not allowed: an interface has no instances and holds no state
The rule for an implementing class: write every abstract method of the interface as public. Default methods are optional; static and private methods are not inherited anyway.

Sealed Types

Sealing: sealed, non-sealed, permits

  • Classes and interfaces can be sealed (Java 17+).
  • sealed: only the permitted subtypes may extend or implement the type.
  • permits: the list of permitted subtypes.
  • Each permitted subtype must pick one of:
    final: the hierarchy ends here;
    sealed: restricts again;
    non-sealed: lifts the restriction, anyone may extend it.
  • Benefit: the compiler knows every subtype (a closed hierarchy).
«sealed interface»Animal+ move()«final»Cat+ move()«non-sealed»Dog+ move()Kangal+ move()Birdnot permitted ✗permits Cat, Dog

Sealed Types

Sealed Interface Example

public sealed interface Animal permits Cat, Dog {
    void move();
}
final class Cat implements Animal {
    public void move() {
        System.out.println("Cat walks silently");
    }
}
non-sealed class Dog implements Animal {
    public void move() {
        System.out.println("Dog runs");
    }
}
class Kangal extends Dog {   // open
    public void move() {
        System.out.println("Kangal guards the flock");
    }
}
// Java 21: switch covers all subtypes,
// no default branch needed
static String kind(Animal h) {
    return switch (h) {
        case Cat k -> "cat";
        case Dog k -> "dog";
    };
}
// in main:
Animal[] animals =
    { new Cat(), new Dog(), new Kangal() };
for (Animal h : animals) {
    h.move();
    System.out.println(kind(h));
}

Output

Cat walks silently
cat
Dog runs
dog
Kangal guards the flock
dog

Comparison

Interfaces vs. Abstract Classes

AspectInterfaceAbstract class
Declare / useinterface · implementsabstract class · extends
MethodsAbstract; Java 8+ default and static, Java 9+ privateBoth abstract and concrete methods
FieldsOnly public static final constants; no instance fieldsAny fields (instance fields included)
ConstructorNoneAllowed; a subclass calls it with super(…)
AccessMembers implicitly public (except private helpers)public, protected, private, package
InheritanceA class implements many interfaces; an interface extends several interfaces → a form of multiple inheritanceA class extends exactly one class
PurposeA shared capability for unrelated classes (“can do”)Grouping classes that share fields (“is a kind of”)
ObjectsNeither can be instantiated with new; both are used as reference types

Comparison

Which One to Choose?

Use an abstract class when

  • The subclasses are close relatives: Square and Circle are both Shapes.
  • You need shared fields and a constructor (name).
  • Part of the common code is ready (template method).

Use an interface when

  • Unrelated classes share a capability: Bird, Plane and Drone are all Flyable.
  • A class needs several capabilities.
  • You want a contract (API) between client code and implementing code.

Often the two are used together:

abstract class Animal implements Noisy { … }
class Duck extends Animal implements Flyable, Swimmable { … }
Java forbids multiple inheritance of classes: if two superclasses define the same field or method differently, it is unclear which one applies (the diamond problem). Interfaces carry no state, so the problem largely disappears; the compiler makes the class resolve any default conflict.

Generics

Why Generics?

With Object

class ObjBox {
    private Object content;
    void put(Object o) { content = o; }
    Object get() { return content; }
}
ObjBox k = new ObjBox();
k.put("Hello");
String s = (String) k.get(); // cast required
k.put(42);                  // no complaint
String t = (String) k.get(); // runtime error
Exception in thread "main"
java.lang.ClassCastException

With a generic class

class Box<T> {
    private T content;
    void put(T x) { content = x; }
    T get() { return content; }
}
Box<String> k = new Box<>();
k.put("Hello");
String s = k.get();          // no cast
k.put(42);                  // won't compile
error: incompatible types:
  int cannot be converted to String
  • Type safety: a value of the wrong type is caught at compile time, not at run time.
  • No explicit cast when reading; one implementation works for every type.

Generics

Generic Classes and Generic Methods

class Box<T> {                    // T: type parameter
    private T content;
    void put(T x) { content = x; }
    T get() { return content; }
}
static <T> void print(T item) {    // generic method
    System.out.println("Item: " + item);
}
// in main:
Box<String> k1 = new Box<>();
k1.put("Hello");
Box<Integer> k2 = new Box<>();
k2.put(42);
int n = k2.get() + 1;               // unboxing
System.out.println(k1.get() + " " + n);
print(3.14);
print('A');

Output

Hello 43
Item: 3.14
Item: A
  • Box<String>: the type argument takes the place of T.
  • new Box<>(): the diamond (<>) infers the type from the left side.
  • A generic method declares its type parameter before the return type: <T>; the type is inferred from the argument.
  • The type argument must be a reference type: Box<int> does not compile; write Box<Integer>.
  • Common names: T type, E element, K key, V value, R result.

Generics

Bounded Type Parameters

<T extends B>: T can only be B or a subtype of it (an upper bound). In return, the method body may use B’s methods.

static <T extends Number> double twice(T x) {
    return x.doubleValue() * 2;   // a Number method
}
// in main:
System.out.println(twice(21));    // T = Integer
System.out.println(twice(1.5));   // T = Double
System.out.println(twice("ten")); // won't compile

First two lines

42.0
3.0

Third line

error: method twice in class Main cannot be
  applied to given types; ... inference variable T
  has incompatible bounds (upper: Number, lower: String)

An interface can be a bound too (still written with extends). The method below finds the largest element of any comparable type (Integer, String…), since it is guaranteed to be able to call compareTo:

static <T extends Comparable<T>> T max(T[] arr)

Generics · Step-by-step code trace

max: Code Trace

two arrays7125best?

Both arrays qualify: Integer and String implement Comparable with their own type. The numbers are autoboxed.

T = Integer7125best7

The compiler infers T as Integer. The first element is the first candidate: best = 7.

T = Integer7125i = 1best12compareTo = 1 > 0 → best = 12

A positive compareTo means the element is larger: best = 12.

T = Integer7125i = 2best12compareTo = -1 → unchanged

Negative result: 5 is smaller, so best stays.

T = Integer7125best12

The loop ends and 12 is returned. The return type is T = Integer: no cast needed.

T = String"apple""pear""cherry"best"apple"

The same method, now with T = String. compareTo now compares in lexicographic order.

T = String"apple""pear""cherry"i = 1best"pear"compareTo = 6 > 0 → best = "pear"

The first differing letters give 'p' − 'a' = 15: positive, so best = "pear".

T = String"apple""pear""cherry"i = 2best"pear"compareTo = -10 → unchanged

'c' − 'p' = −13: negative, best stays.

T = String"apple""pear""cherry"best"pear"

pear is returned. One implementation worked for two types; thanks to the bound, the compareTo call is checked at compile time.

static <T extends Comparable<T>> T max(T[] arr) {
    T best = arr[0];
    for (int i = 1; i < arr.length; i++) {
        if (arr[i].compareTo(best) > 0) {
            best = arr[i];
        }
    }
    return best;
}
// in main:
Integer[] numbers = {7, 12, 5};
String[] fruits = {"apple", "pear", "cherry"};
System.out.println(max(numbers));
System.out.println(max(fruits));

Generics

Wildcards (?) and Invariance

static double sum(List<? extends Number> list) {
    double t = 0;
    for (Number n : list) t += n.doubleValue();  // read
    return t;
}
static void fill(List<? super Integer> list) {
    list.add(1);                                 // write
    list.add(2);
}
// in main:
List<Integer> ints = Arrays.asList(1, 2, 3);
List<Number> numbers = new ArrayList<>();
fill(numbers);
numbers.add(2.5);
System.out.println(sum(ints) + " " + numbers);
// List<Number> x = ints;   error

Output

6.0 [1, 2, 2.5]
IntegerNumber✓ is-aList<Integer>List<Number>✗ noList<Integer>List<? extends Number>✓
  • Invariance: List<Integer> is not a subtype of List<Number>; if it were, you could add 2.5 to the list.
  • ?: some unknown type.
  • ? extends T: the list produces values; you read from it.
  • ? super T: the list consumes values; you write to it.
  • Rule (PECS): Producer Extends, Consumer Super.

Generics

Type Erasure

class Box<T> {
    private T content;
    // T make() { return new T(); }   error
}
// in main:
Box<String> a = new Box<>();
Box<Integer> b = new Box<>();
System.out.println(a.getClass() == b.getClass());
System.out.println(a.getClass().getName());

Output

true
Box
source codeBox<String> kString s = k.get();javacchecks,erasesbytecodeBox kString s = (String) k.get();
  • Generic type information is mostly for the compiler; after checking it is erased (type erasure). T becomes Object (or its bound).
  • At run time Box<String> and Box<Integer> are the same class.
  • That is why you cannot write new T() (unexpected type) or new T[10] (generic array creation).

Annotations

Annotations

An annotation is metadata attached to a class, method, field or parameter. It changes no behavior by itself; the compiler, tools or the running program (via reflection) read it.

AnnotationRead byEffect
@OverridecompilerError if the supertype has no such method
@DeprecatedcompilerObsolete element; code using it gets a warning
@SuppressWarnings("unchecked")compilerSilences the named warning
@FunctionalInterfacecompilerChecks that the interface has exactly one abstract method
@Test (JUnit)test toolFinds and runs test methods
@FunctionalInterface
interface Operation {
    int apply(int a, int b);
    int negate(int a);   // 2nd abstract
}
error: Unexpected @FunctionalInterface annotation
  Operation is not a functional interface
    multiple non-overriding abstract methods
    found in interface Operation

Annotations

Custom Annotations and Reflection

@Retention(RetentionPolicy.RUNTIME)  // read at run time
@Target(ElementType.METHOD)          // methods only
@interface Task {
    String author();
    int priority() default 1;
}
class Jobs {
    @Task(author = "Ayşe", priority = 3)
    public void backup() { System.out.println("Backup done"); }
    public void clean() { System.out.println("Cleaned"); }
}
// in main (reflection, java.lang.reflect.Method):
Jobs jobs = new Jobs();
for (Method m : Jobs.class.getDeclaredMethods()) {
    Task g = m.getAnnotation(Task.class);
    if (g != null) {
        System.out.println(m.getName() + ", "
            + g.author() + ", " + g.priority());
        m.invoke(jobs);
    }
}

Output

backup, Ayşe, 3
Backup done
@RetentionWhere is it kept?
SOURCESource only (@Override)
CLASSIn the .class file; invisible to reflection
RUNTIMERead via reflection at run time
  • Reflection: a program inspects its own classes, methods and annotations at run time.
  • It weakens compiler checks and slows code down; use it only when truly needed, as frameworks do.

Design Patterns

Design Patterns

  • A design pattern is a proven, reusable solution template for a recurring design problem. It is not code to copy but a shared vocabulary that names the problem and its trade-offs.
  • Patterns separate responsibilities and reduce coupling between classes: one part can be changed without touching the others, and tested on its own.
Creationalhow are objects created?Singleton, Factory, BuilderStructuralhow are objects composed?Adapter, Decorator, FacadeBehavioralhow do objects communicate?Observer, Strategy, Command
A pattern helps only if it solves a real problem. An unnecessary pattern just complicates the program. Patterns are concrete applications of more general design principles such as “low coupling” and “composition over inheritance”.

Design Patterns

Singleton: A Single Instance

public final class Settings {
  private static final Settings INSTANCE = new Settings();
  private Settings() {
    System.out.println("Settings created");
  }
  public static Settings getInstance() { return INSTANCE; }
}
// main:
System.out.println("main started");
Settings a = Settings.getInstance();
Settings b = Settings.getInstance();
System.out.println(a == b);
Output
main started
Settings created
true
  • The class has only one instance, accessed from a single place.
  • private constructor: new Settings() from outside does not compile.
  • The JVM creates the instance once, when the class is first used: this is thread-safe.
  • It acts like a hidden global variable: swapping in another object gets hard. Passing the object to the constructor (dependency injection) is usually better.

Design Patterns

Factory

interface Shape { double area(); }
class Square implements Shape { … }   // area: a * a
class Circle implements Shape { … }  // area: π r²

class ShapeFactory {
  static Shape create(String kind, double size) {
    switch (kind.toLowerCase(Locale.ROOT)) {
      case "square":  return new Square(size);
      case "circle": return new Circle(size);
      default:      return null;  // unknown kind
    }
  }
}
Shape s = ShapeFactory.create("Square", 3);
System.out.println(s.area());   // 9.0
  • Object creation is gathered in one place; the caller knows the interface (Shape), not the concrete class (Square).
  • Adding a new shape changes only the factory. For an unknown kind it returns null; the caller checks the result.
  • Locale.ROOT: under a Turkish locale "CIRCLE".toLowerCase() gives "cırcle", which does not match.
  • Writing a factory for objects that are already simple to create is needless complexity.
Unknown kind
Shape u = ShapeFactory.create("triangle", 2);
System.out.println(u == null);   // true

Design Patterns

Observer

interface Observer { void update(int degrees); }

class Station {
  private final List<Observer> list = new ArrayList<>();
  void add(Observer g) { list.add(g); }
  void setTemp(int d) {
    for (Observer g : list) g.update(d);
  }
}
Stationsubjectdisplay observeralert observerlogging observersetTemp → update(d) on each observer
  • A one-to-many relationship: when the subject changes, all registered observers are notified.
  • The subject does not know the observers’ concrete classes; it calls only the interface.
  • Observers can be small objects that print to the console: one shows the reading, one raises an alert, one logs it.

Design Patterns · Step-by-step code trace

The Observer Pattern Step by Step

interface Observer { void update(int degrees); }
class Station {
  private final List<Observer> list = new ArrayList<>();
  void add(Observer g) { list.add(g); }
  void setTemp(int d) {
    for (Observer g : list) g.update(d);
  }
}
// main:
Station st = new Station();
st.add(d -> System.out.println("Display: " + d + " °C"));
st.add(d -> { if (d > 30) System.out.println("Alert: hot!"); });
st.setTemp(25);
st.setTemp(34);
stlast: –list

The subject object is created; the observer list is empty.

stlast: –list[0] display

The first observer is a lambda implementing the single method of the Observer interface. It is added to the list; it does not run.

stlast: –list[0] display[1] alert (d > 30)

The second observer is added: it speaks up only above 30 degrees.

stlast: 25list[0] display[1] alert (d > 30)

setTemp(25): the loop walks the list from the start.

stlast: 25list[0] display[1] alert (d > 30)

The display observer’s update(25) is called.

stlast: 25list[0] display[1] alert (d > 30)

The alert observer is notified too, but 25 > 30 is false: it prints nothing.

stlast: 34list[0] display[1] alert (d > 30)

A new reading: 34.

stlast: 34list[0] display[1] alert (d > 30)

The display prints the new value.

stlast: 34list[0] display[1] alert (d > 30)

This time the condition holds and the alert is printed. Station never knew what any observer does; adding a new observer does not change its code.

Design Patterns

Strategy

interface Discount { double apply(double amount); }

class StudentDiscount implements Discount {
  public double apply(double amount) { return amount * 0.90; }
}
class Checkout {
  private final Discount strategy;
  Checkout(Discount strategy) { this.strategy = strategy; }
  double due(double amount) {
    return strategy.apply(amount);
  }
}
Checkout k = new Checkout(new StudentDiscount());
System.out.println(k.due(250));   // 225.0
  • Interchangeable algorithms are placed behind a common interface.
  • Behavior changes with a different strategy object while Checkout’s code stays the same.
  • Since the interface has one method, a strategy can also be a lambda: new Checkout(t -> t * 0.90).
  • Sorting with a Comparator is also a strategy.

Design Patterns · Step-by-step code trace

The Strategy Pattern Step by Step

interface Discount { double apply(double amount); }
class Checkout {
  private final Discount strategy;
  Checkout(Discount strategy) { this.strategy = strategy; }
  double due(double amount) { return strategy.apply(amount); }
}
// main:
Checkout student = new Checkout(t -> t * 0.90);
Checkout promo = new Checkout(t -> t >= 200 ? t - 50 : t);
System.out.println(student.due(250));
System.out.println(promo.due(250));
System.out.println(promo.due(120));
// fixed strategy: Checkout tested alone
System.out.println(new Checkout(t -> 7).due(100));
studentt × 0.90promot ≥ 200 ? t − 50 : t

Checkout does not compute the discount itself; it asks the strategy object passed to its constructor. The first checkout gets a 10% discount.

studentt × 0.90promot ≥ 200 ? t − 50 : t

The same Checkout class with another strategy: 50 TL off for 200 TL or more.

studentt × 0.90promot ≥ 200 ? t − 50 : tdue(250) → 225.0

due delegates to the strategy: 250 × 0.90 = 225.0.

studentt × 0.90promot ≥ 200 ? t − 50 : tdue(250) → 200.0

The promo strategy: 250 ≥ 200 → 250 − 50 = 200.0.

studentt × 0.90promot ≥ 200 ? t − 50 : tdue(120) → 120.0

120 < 200: no discount. The behavior changed without touching Checkout’s code.

studentt × 0.90promot ≥ 200 ? t − 50 : tfixed checkoutalways 7due(100) → 7.0

A fixed strategy is plugged in instead of a real discount rule: whatever the amount, the result is 7.0. This shows only that Checkout delegates correctly to its strategy.

Design Patterns

MVC: Model, View, Controller

User inputControllerModel (data)View (screen)updatesrefreshesreads data
  • Model: data and rules (Student, getName()); unaware of the screen, testable without it.
  • View: only displays (StudentView.show(name) prints to the console).
  • Controller: takes input and manages the model and view; update() reads the model and passes the result to the view.
  • Frameworks implement MVC in different ways; there is no single “right” class structure.
Student m = new Student("Ayşe");
StudentView g = new StudentView();
StudentController d =
    new StudentController(m, g);
d.update();  // g.show(m.getName())
Output
Student: Ayşe

Design Patterns

Patterns: When Not to Use Them

Turning a Singleton into a global variable

Mutable state reachable from everywhere couples the parts of a program to each other.

Needless factory

Writing a separate class for something as simple as new Point(3, 4).

Needless observer

Building an event system where one direct method call would do; the flow becomes hard to follow.

Using a pattern for its own sake

Problem first, pattern second: “Which change does it make easier? Which dependency does it reduce?”

Strategies and dependencies passed in from outside let you replace a real part with a simple fake object (like plugging a fixed strategy into Checkout). A class that is hard to test on its own usually needs its design revisited.

Summary

Summary

ConceptEssence
AbstractionHide the details and define “what”; leave “how” to subclasses
Abstract classabstract class; no instances; may hold fields, constructors, abstract and concrete methods
Abstract methodNo body, ends with ;; a concrete subclass must implement it
InterfaceA contract; methods implicitly public abstract, fields public static final
implementsOne extends, many implements; implementing methods are public
Lambda(parameters) -> expression; assigned to a functional interface (Java 8+)
default / static / privateInterface methods with bodies (Java 8 / 8 / 9)
sealedPermitted subtypes via permits; each is final, sealed or non-sealed
GenericsBox<T>, <T extends B>, wildcard ?; checked at compile time, type information erased afterwards
AnnotationsMetadata such as @Override; RUNTIME annotations are read via reflection
Design patternsSingleton, Factory, Observer, Strategy, MVC: proven solution templates

Summary

Related Pages

Polymorphism

The basics of dynamic binding with references of interface and abstract class types.

Writing @Override when implementing an abstract or interface method catches a misspelled name or wrong parameters at once, as a compile error.

Summary

Common Mistakes (1): Abstract Classes

Instantiating an abstract class

new Shape("?") → Shape is abstract; cannot be instantiated. Use a concrete subclass.

Forgetting an abstract method

Circle is not abstract and does not override abstract method draw() in Shape. Write the method or make the class abstract.

A body on an abstract method

abstract void draw() { } → abstract methods cannot have a body. Either abstract or a body.

Not making the class abstract

class Shape { abstract void draw(); } → Shape is not abstract and does not override abstract method draw() in Shape.

Conflicting modifiers

abstract final, private abstract, static abstract → illegal combination of modifiers.

Getting the signature wrong

double Area() or double area(int x) is a new method; the abstract area() is still missing. @Override catches this.

Summary

Common Mistakes (2): Interfaces

Forgetting public

void draw() { … } → attempting to assign weaker access privileges; was public. Write interface methods as public.

Changing a constant

GeometricShape.SIDES = 5; → cannot assign a value to static final variable SIDES.

Extending two classes

class C extends A, B → '{' expected. One extends, many implements.

A method the reference type lacks

Flyable u = new Duck(); u.swim(); → cannot find symbol. Call a method through a reference whose type knows it.

Conflicting default methods

class Clerk inherits unrelated defaults for greet(). Override the method in the class.

Sealing errors

Unpermitted subtype: class is not allowed to extend sealed class: Animal. Permitted subtype without a modifier: sealed, non-sealed or final modifiers expected.

Summary

Practice Problems (1): Does It Compile?

// (a)
abstract class A {
    void f() { System.out.println("f"); }
}
// (b)
class B { abstract void g(); }
// (c)
interface I { int X = 1; }
...  I.X++;
// (d)
interface J { void h(); }
class C implements J { void h() { } }
// (e)
abstract class D { abstract void k(); }
abstract class E extends D { }
  1. For each fragment (a)–(e): does it compile? If not, what is the error?
  2. Which of the compiling fragments can be instantiated with new?
Show answers
  1. (a) Compiles: an abstract class without abstract methods is valid. (b) Error: B is not abstract and does not override abstract method g() in B. (c) Error: cannot assign a value to static final variable X. (d) Error: h() is not public → weaker access privileges; was public. (e) Compiles: E is abstract too, so it need not write k().
  2. None: A and E are abstract, so new A() and new E() are compile errors too.

Summary

Practice Problems (2): What Is the Output?

interface Noisy {
    default String sound() { return "..."; }
}
abstract class Animal implements Noisy {
    Animal() { System.out.print("A "); }
    abstract String name();
}
class Cat extends Animal {
    Cat() { System.out.print("C "); }
    String name() { return "cat"; }
    public String sound() { return "meow"; }
}
class Fish extends Animal {
    String name() { return "fish"; }
}
// in main:
Animal[] d = { new Cat(), new Fish() };
System.out.println();
for (Animal h : d)
    System.out.println(h.name() + ": " + h.sound());
  1. What does the program print?
  2. Why does Fish compile even though it does not write sound()?
  3. What happens if public is removed from sound() in Cat?
  4. Does Noisy s = new Fish(); s.name(); compile?
Show answers
  1. A C A, then cat: meow and fish: .... Creating a Cat runs the Animal constructor first (A), then the Cat constructor (C); for Fish only A.
  2. sound() is default, not abstract: Fish inherits it and writes the only abstract method, name().
  3. Compile error: weaker access privileges; was public.
  4. No: cannot find symbol. Type Noisy knows only sound().

Summary

Exercises (1)

  1. Write an abstract class Employee: a name field, a constructor, an abstract double salary() and an info() that prints the name and salary. Subclasses: FullTime (30000 a month), Hourly (120 hours × 200). Call info() on an Employee[] array.
  2. Interface Shape2D: an abstract double area() and a default summary() returning "Area: " + area(). What does summary() return for Triangle(6, 4)?
  3. interface Calc { static int sum(int a, int b) … } and class Simple implements Calc {}: what do Calc.sum(3, 4) and Simple.sum(3, 4) give?
Answers / hints
  1. For example double salary() { return hours * rate; }; the output is Ayşe: 30000.0 / Ali: 24000.0.
  2. public double area() { return base * height / 2; } → Area: 12.0.
  3. 7; the second does not compile: cannot find symbol (static interface methods are not inherited).

Summary

Exercises (2)

  1. Write sealed abstract class Shape permits Square, Circle, with Square final and Circle non-sealed. Do Ellipse extends Circle and Triangle extends Shape compile?
  2. Abstract class or interface? (a) a Vehicle with a plate number and a constructor; (b) a shared save() capability of Student and Invoice; (c) a Fish that is an Animal and can swim.
  3. Inside class Square implements GeometricShape someone wrote public void Draw() { … }. What happens? And with @Override above the method?
Answers / hints
  1. Ellipse compiles (Circle is non-sealed); Triangle: class is not allowed to extend sealed class: Shape.
  2. (a) abstract class (shared fields + constructor); (b) interface (unrelated classes); (c) class Fish extends Animal implements Swimmable.
  3. Draw ≠ draw (case matters): Square is not abstract and does not override abstract method draw() in GeometricShape. With @Override you also get method does not override or implement a method from a supertype.

Summary

References

  • Oracle, The Java Tutorials: Abstract Methods and Classes; Interfaces; Default Methods; Lambda Expressions.
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition (8.1.1.1 abstract Classes, 8.1.1.2 sealed Classes, Chapter 9: Interfaces, 15.27 Lambda Expressions).
  • Oracle, JEP 409: Sealed Classes (Java 17) and JEP 441: Pattern Matching for switch (Java 21).
  • P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 10: Object-Oriented Programming: Polymorphism and Interfaces).
  • K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly (Chapter 8: Interfaces and Abstract Classes).
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapters 5–6).
  • E. Gamma, R. Helm, R. Johnson and J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994.

The End

Chapter 4.5: Abstract Classes and Interfaces
Previous: Chapter 4.4: Polymorphism · Next: Chapter 5: Collections
1 / 1 Sercan KÜLCÜ. All rights reserved.