Chapter 4.5: Abstract Classes and Interfaces
Introduction
Learning Outcomes
Declare abstract classes and methods; explain why an abstract class cannot be instantiated and what a subclass must implement.
Trace code to show a concrete method of an abstract class calling an abstract method implemented in a subclass.
Declare an interface, implement one or more interfaces with implements, and use default, static and private methods.
Recognize a functional interface; write single-method behavior as a lambda expression and trace when the lambda runs.
Explain which problem Singleton, Factory, Observer, Strategy and MVC solve and how they rely on interfaces.
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.
The common concept on top, the details below.
Abstract Classes
Abstract Class
- Declared with the
abstractkeyword: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(); }
moveIts body is ready. Subclasses inherit it as is, or override it if they want.
drawIt 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(...).
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
Shape’s area() has no body. If new Shape() were allowed, the call s1.area() would have no code to run.
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
| Code | Result |
|---|---|
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 abstract | illegal 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
new Square(3): first a Square object is allocated on the heap. Fields get default values: null and 0.0.
Square’s constructor runs. The parameter is side = 3.0 (the int 3 widened to double).
The first step is super("Square"): the superclass constructor is called. An abstract class can have a constructor too.
The Shape constructor runs. No separate Shape object is created: the Shape part of the same object is being built.
this.name = name: the object’s name field becomes "Square".
The message is printed. The Shape constructor ends and its frame leaves the stack.
Back in Square’s constructor: this.side = 3.0. The object is now fully built.
The object’s reference is stored in s. The variable’s type is Shape (abstract); the object it points to is a Square.
s.area(): area() is abstract in Shape. At run time the object’s type decides → Square.area(): 3.0 · 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
The variable type is Beverage (abstract), the object a Tea. Tea is concrete because it implements the only abstract method, brew().
Tea has no prepare() → the concrete method inherited from Beverage runs. final: subclasses cannot change this order.
Step 1: boilWater(), that is this.boilWater(), is called.
The concrete boilWater() in Beverage runs.
Step 2: brew(). It has no body in Beverage, but this is a Tea object…
…so Tea.brew() runs. Code in the abstract class can call subclass code that has not even been written yet.
Step 3: the serving message is printed.
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
interfacekeyword. - Interface methods are public, whether or not you write
public. - Unless it is
static,defaultorprivate, a method is implicitly abstract. - The only fields allowed are
public static finalconstants.
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.
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
implementskeyword. - It must implement all the abstract methods of the interface, or be
abstractitself. - Missing method:
Square is not abstract and does not override abstract method draw() in GeometricShape. - The implementing method must be
public. If you writevoid 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, …). extendscomes first, thenimplements.class C extends A, B→error: '{' expected.
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
One Duck object is created on the heap; o points to it.
Assignment does not copy the object: u points to the same object. A Duck is a Flyable → the conversion is automatic.
y points to the same object too. One object, viewed through three different types.
u.fly(): u has type Flyable, so only fly() can be called on it. What runs is the object’s own fly().
y.swim(): type Swimmable knows swim().
Had we written u.swim(): error: cannot find symbol. The object has swim(), but the compiler looks at the reference type.
o has type Duck: everything is accessible, including the field name.
== 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
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 saysy.pay(total)and the object does the rest.- A new payment type (
Crypto) just implements the interface;buynever 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<>();
Interfaces · Step-by-step code trace
Payment Interface: Code Trace
The parameter y has an interface type; the object passed in is a CreditCard.
y.pay(total) is bound dynamically: the object is a card, so CreditCard.pay() runs.
The call ends; nothing refers to the card object any more, so the garbage collector may reclaim it.
The same buy, this time with a Transfer object.
This time the same line runs Transfer.pay(), which adds a 5 TL fee: 125.0.
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.
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.
@FunctionalInterfaceis 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");
Hello Ayşe
Lambda Expressions
Built-in Functional Interfaces
You need not write an interface every time: package java.util.function provides the common shapes.
| Interface | Input | Output | Method | Typical use |
|---|---|---|---|---|
Consumer<T> | one value | none | accept | printing, saving |
Supplier<T> | none | one value | get | producing a value |
Function<T, R> | one value | one value | apply | transforming |
Predicate<T> | one value | boolean | test | filtering, 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));Consumer ran 4 7 false
Lambda Expressions · Step-by-step code trace
When Does a Lambda Run? Step by Step
The lambda is stored as a Predicate<Integer> object; its body has not run yet. isEven is a reference to that behavior.
The list: 3, 8, 5, 12.
The result list starts empty.
Next element: s = 3.
isEven.test(3) runs the lambda body: 3 % 2 == 0 → false.
Next element: s = 8.
isEven.test(8) runs the lambda body: 8 % 2 == 0 → true.
The condition holds: 8 is added to the result list.
Next element: s = 5.
isEven.test(5) runs the lambda body: 5 % 2 == 0 → false.
Next element: s = 12.
isEven.test(12) runs the lambda body: 12 % 2 == 0 → true.
The condition holds: 12 is added to the result list.
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());
8 [2, 4, 6] [1, 4, 9, 16, 25, 36, 49]
- The lambda is assigned to a functional interface type:
IntBinaryOperatortakes twoints and returns anint; the call isapplyAsInt. filter(s -> s % 2 == 0)keeps the even numbers;maptransforms..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();
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
finalor effectively final: never reassigned afterwards. - Inside a lambda,
thisis 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();
[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
Cart wrote only the two abstract methods, not isEmpty().
Lookup finds no isEmpty() in Cart, so the interface’s default body runs.
The default method calls the abstract size(); the object decides which body runs: Cart.size() → 0.
0 == 0: true.
add is Cart’s version: count becomes 1.
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
PIgivescannot find symbol; the constant lives inMath: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
Both interfaces bring a default body for work(). To resolve the ambiguity, OfficeMachine writes the method itself.
The reference type is Printer, but the object is an OfficeMachine: the class’s own work() runs.
Scanner.super.work(): calls the default body of the named interface.
Then Printer’s. The class chooses which versions to use and in what order.
Finally the class adds its own step: behavior that combines both capabilities.
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
privatemethods 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 insideReport. - Flow:
print()(default) →title()(private) +content()(the abstract method Report implements).
Interface Methods
Interface Members: Summary
| Member | Example | Implicit modifiers | Body | Java |
|---|---|---|---|---|
| Abstract method | void draw(); | public abstract | none | 1.0 |
| Constant | int SIDES = 4; | public static final | — | 1.0 |
| Default method | default boolean isEmpty() {…} | public | yes | 8 |
| static method | static double squareArea(…) {…} | public | yes | 8 |
| Private method | private String title() {…} | inside the interface only | yes | 9 |
| Instance field, constructor | — | Not allowed: an interface has no instances and holds no state | ||
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 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
| Aspect | Interface | Abstract class |
|---|---|---|
| Declare / use | interface · implements | abstract class · extends |
| Methods | Abstract; Java 8+ default and static, Java 9+ private | Both abstract and concrete methods |
| Fields | Only public static final constants; no instance fields | Any fields (instance fields included) |
| Constructor | None | Allowed; a subclass calls it with super(…) |
| Access | Members implicitly public (except private helpers) | public, protected, private, package |
| Inheritance | A class implements many interfaces; an interface extends several interfaces → a form of multiple inheritance | A class extends exactly one class |
| Purpose | A shared capability for unrelated classes (“can do”) | Grouping classes that share fields (“is a kind of”) |
| Objects | Neither 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 { … }
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 ofT.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; writeBox<Integer>. - Common names:
Ttype,Eelement,Kkey,Vvalue,Rresult.
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
Both arrays qualify: Integer and String implement Comparable with their own type. The numbers are autoboxed.
The compiler infers T as Integer. The first element is the first candidate: best = 7.
A positive compareTo means the element is larger: best = 12.
Negative result: 5 is smaller, so best stays.
The loop ends and 12 is returned. The return type is T = Integer: no cast needed.
The same method, now with T = String. compareTo now compares in lexicographic order.
The first differing letters give 'p' − 'a' = 15: positive, so best = "pear".
'c' − 'p' = −13: negative, best stays.
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]
- Invariance:
List<Integer>is not a subtype ofList<Number>; if it were, you could add2.5to 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
- Generic type information is mostly for the compiler; after checking it is erased (type erasure).
TbecomesObject(or its bound). - At run time
Box<String>andBox<Integer>are the same class. - That is why you cannot write
new T()(unexpected type) ornew 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.
| Annotation | Read by | Effect |
|---|---|---|
@Override | compiler | Error if the supertype has no such method |
@Deprecated | compiler | Obsolete element; code using it gets a warning |
@SuppressWarnings("unchecked") | compiler | Silences the named warning |
@FunctionalInterface | compiler | Checks that the interface has exactly one abstract method |
@Test (JUnit) | test tool | Finds 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 OperationAnnotations
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
@Retention | Where is it kept? |
|---|---|
SOURCE | Source only (@Override) |
CLASS | In the .class file; invisible to reflection |
RUNTIME | Read 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.
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);
main started Settings created true
- The class has only one instance, accessed from a single place.
privateconstructor: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.
Shape u = ShapeFactory.create("triangle", 2);
System.out.println(u == null); // trueDesign 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); } }
- 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);
The subject object is created; the observer list is empty.
The first observer is a lambda implementing the single method of the Observer interface. It is added to the list; it does not run.
The second observer is added: it speaks up only above 30 degrees.
setTemp(25): the loop walks the list from the start.
The display observer’s update(25) is called.
The alert observer is notified too, but 25 > 30 is false: it prints nothing.
A new reading: 34.
The display prints the new value.
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
Comparatoris 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));
Checkout does not compute the discount itself; it asks the strategy object passed to its constructor. The first checkout gets a 10% discount.
The same Checkout class with another strategy: 50 TL off for 200 TL or more.
due delegates to the strategy: 250 × 0.90 = 225.0.
The promo strategy: 250 ≥ 200 → 250 − 50 = 200.0.
120 < 200: no discount. The behavior changed without touching Checkout’s code.
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
- 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())
Student: Ayşe
Design Patterns
Patterns: When Not to Use Them
Mutable state reachable from everywhere couples the parts of a program to each other.
Writing a separate class for something as simple as new Point(3, 4).
Building an event system where one direct method call would do; the flow becomes hard to follow.
Problem first, pattern second: “Which change does it make easier? Which dependency does it reduce?”
Checkout). A class that is hard to test on its own usually needs its design revisited.Summary
Summary
| Concept | Essence |
|---|---|
| Abstraction | Hide the details and define “what”; leave “how” to subclasses |
| Abstract class | abstract class; no instances; may hold fields, constructors, abstract and concrete methods |
| Abstract method | No body, ends with ;; a concrete subclass must implement it |
| Interface | A contract; methods implicitly public abstract, fields public static final |
| implements | One extends, many implements; implementing methods are public |
| Lambda | (parameters) -> expression; assigned to a functional interface (Java 8+) |
| default / static / private | Interface methods with bodies (Java 8 / 8 / 9) |
| sealed | Permitted subtypes via permits; each is final, sealed or non-sealed |
| Generics | Box<T>, <T extends B>, wildcard ?; checked at compile time, type information erased afterwards |
| Annotations | Metadata such as @Override; RUNTIME annotations are read via reflection |
| Design patterns | Singleton, Factory, Observer, Strategy, MVC: proven solution templates |
Summary
Related Pages
The basics of dynamic binding with references of interface and abstract class types.
@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
new Shape("?") → Shape is abstract; cannot be instantiated. Use a concrete subclass.
Circle is not abstract and does not override abstract method draw() in Shape. Write the method or make the class abstract.
abstract void draw() { } → abstract methods cannot have a body. Either abstract or a body.
class Shape { abstract void draw(); } → Shape is not abstract and does not override abstract method draw() in Shape.
abstract final, private abstract, static abstract → illegal combination of modifiers.
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
publicvoid draw() { … } → attempting to assign weaker access privileges; was public. Write interface methods as public.
GeometricShape.SIDES = 5; → cannot assign a value to static final variable SIDES.
class C extends A, B → '{' expected. One extends, many implements.
Flyable u = new Duck(); u.swim(); → cannot find symbol. Call a method through a reference whose type knows it.
class Clerk inherits unrelated defaults for greet(). Override the method in the class.
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 { }
- For each fragment (a)–(e): does it compile? If not, what is the error?
- Which of the compiling fragments can be instantiated with
new?
Show answers
- (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 notpublic→weaker access privileges; was public. (e) Compiles: E is abstract too, so it need not writek(). - None: A and E are abstract, so
new A()andnew 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());
- What does the program print?
- Why does
Fishcompile even though it does not writesound()? - What happens if
publicis removed fromsound()inCat? - Does
Noisy s = new Fish(); s.name();compile?
Show answers
A C A, thencat: meowandfish: .... Creating a Cat runs the Animal constructor first (A), then the Cat constructor (C); for Fish only A.sound()isdefault, not abstract: Fish inherits it and writes the only abstract method,name().- Compile error:
weaker access privileges; was public. - No:
cannot find symbol. TypeNoisyknows onlysound().
Summary
Exercises (1)
- Write an abstract class
Employee: anamefield, a constructor, an abstractdouble salary()and aninfo()that prints the name and salary. Subclasses:FullTime(30000 a month),Hourly(120 hours × 200). Callinfo()on anEmployee[]array. - Interface
Shape2D: an abstractdouble area()and a defaultsummary()returning"Area: " + area(). What doessummary()return forTriangle(6, 4)? interface Calc { static int sum(int a, int b) … }andclass Simple implements Calc {}: what doCalc.sum(3, 4)andSimple.sum(3, 4)give?
Answers / hints
- For example
double salary() { return hours * rate; }; the output isAyşe: 30000.0/Ali: 24000.0. public double area() { return base * height / 2; }→Area: 12.0.7; the second does not compile:cannot find symbol(static interface methods are not inherited).
Summary
Exercises (2)
- Write
sealed abstract class Shape permits Square, Circle, with Squarefinaland Circlenon-sealed. DoEllipse extends CircleandTriangle extends Shapecompile? - Abstract class or interface? (a) a
Vehiclewith a plate number and a constructor; (b) a sharedsave()capability ofStudentandInvoice; (c) aFishthat is an Animal and can swim. - Inside
class Square implements GeometricShapesomeone wrotepublic void Draw() { … }. What happens? And with@Overrideabove the method?
Answers / hints
Ellipsecompiles (Circle isnon-sealed);Triangle:class is not allowed to extend sealed class: Shape.- (a) abstract class (shared fields + constructor); (b) interface (unrelated classes); (c)
class Fish extends Animal implements Swimmable. Draw≠draw(case matters):Square is not abstract and does not override abstract method draw() in GeometricShape. With@Overrideyou also getmethod 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.