Object-Oriented Programming with Java · Lecture Notes
Chapter 4.5: Abstract Classes and Interfaces
Inheritance gathers shared code in the superclass, and polymorphism makes the same call run the method of each object's own class. These two tools leave one gap: a superclass sometimes cannot write the body of a method. The area of a general “shape” cannot be computed; only a square, a circle or a triangle knows the formula. Java offers two tools for this situation: the abstract class and the interface. Both say “what to do” and leave “how to do it” to the subtypes. These notes first cover the abstract class and the abstract method, then the interface, the methods with bodies in interfaces, and sealed types. Lambda expressions, the short notation for interfaces with a single method, generic classes with type parameters, and annotations that add metadata to code are among the topics too. The last section explains five design patterns, most of them built on interfaces (Singleton, Factory, Observer, Strategy and MVC), with small console programs. All programs were compiled and run with JDK 21; the outputs, the final values in the trace tables and the compiler messages come from these runs.
Learning outcomes
- Abstract class
- Define
abstractclasses and methods; explain why an object cannot be created from an abstract class and which methods a concrete subclass must write. - Template method
- Show, by tracing the code step by step, that a concrete method of an abstract class calls an abstract method written in the subclass.
- Interface
- Define an
interface; implement one or several interfaces withimplements; usedefault,staticandprivateinterface methods. - Lambda
- Recognize a functional interface; write a one-method behavior as a lambda expression and trace when the lambda runs.
- Design decision
- Recognize sealed types; decide whether a problem needs an interface or an abstract class (or both); use generic types and annotations.
- Design patterns
- Explain which problem the Singleton, Factory, Observer, Strategy and MVC patterns solve and how they rely on interfaces.
4.5.1Abstraction
Someone who drives a car knows the steering wheel, the gear stick and the pedals. They do not have to know how the fuel burns inside the engine or how the gearbox changes its gears. The face the car presents to the driver is simple; the complex detail stays behind that face. Moreover, the same face is the same on different cars. Someone who can drive a gasoline car can drive an electric car too, because both obey the contract of steering wheel and pedals.
Abstraction is hiding complex details and showing only the essential features. In programming, abstraction separates “what” a job does from “how” it does it.
The same separation is useful in a program. Suppose a drawing program wants to compute the total area of the shapes on the screen. Every shape has an area; this is the essential property of the concept “shape”. But the area of a general shape cannot be computed. The formula is a · a for a square, π · r² for a circle, b · h / 2 for a triangle. Only the concrete shape knows the formula. Figure 4.5.1 draws this situation: the common concept is at the top, the detail at the bottom.
The code that computes the total area should rely only on the knowledge that “every shape has an area() method”. It does not ask whether a shape is a square or a circle; it asks each shape for its area. If a hexagon is added to the program tomorrow, the summing code does not change; only the new class is written. This is the gain of abstraction: the code that uses a type depends on the concept, not on the detail.
Java has two tools for abstraction: abstract classes (abstract class) and interfaces (interface). Both say what is to be done and leave how to do it to the subclasses. The difference between them in brief is this. An abstract class is the common ancestor of closely related classes; it can have fields, a constructor and ready-made methods. An interface is a contract that gives a common ability to classes that are not related to each other.
4.5.2Abstract classes
In inheritance, the superclass carries the shared fields and methods of the subclasses. Class Shape can write the shared name field and the move method of all shapes. It gets stuck at the area() method. What should the body be? Writing return 0; is wrong. No shape's area is really 0. If a subclass forgets to override the method, the program silently produces a wrong result. The right solution is not to write the body at all and to tell the compiler so explicitly.
4.5.2.1Defining an abstract class
An abstract class is a class declared with the abstract keyword from which no object can be created. An abstract class can contain both abstract methods (without a body) and concrete methods (with a body). A subclass that writes all the abstract methods is called a concrete class; objects can be created only from such a class.
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();
}This Shape class has two methods. move is concrete: its body is ready. Subclasses inherit it as it is, or override it if they wish. Since moving a shape to a point requires the same work for every shape, writing the body once in the superclass is right. draw is abstract: it has only a signature. Drawing a square and drawing a circle are different jobs; so every concrete subclass must write its own draw() body.
An abstract class is like an unfinished plan. Some rooms are finished, for others only the place is fixed. The architect who takes over the plan fills the empty places without touching the finished rooms. The small program below completes the class with a Square and calls both methods:
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();
}
class Square extends Shape {
void draw() { System.out.println("Drawing a square"); }
}
public class D03 {
public static void main(String[] args) {
Shape s = new Square();
s.move(3, 4);
s.draw();
}
}Moved to (3, 4)
Drawing a squareSquare has written only draw(); it gets move from Shape. The type of the variable is the abstract Shape, but the object it points to is a Square. In the call s.draw(), which body runs is chosen at run time by the class of the object, as in polymorphism. This decision is called dynamic binding.
The other properties of an abstract class are the same as those of an ordinary class. It can have fields, constructors and static members. Other classes extend it with extends. Figure 4.5.2 draws a Shape class with four methods and the three concrete classes that extend it. The drawing is in UML (Unified Modeling Language) notation.
name field, the constructor and the getName() method of Shape are concrete; area() and draw() are abstract. Square, Circle and Rectangle carry their own fields and write area() with their own formulas.The gain of the design in the figure is that the shared state (the fields) and behavior are gathered in a single place. The name field and the getName() that reads it are not written separately in three classes. The subclasses fill in the abstract methods according to their needs. That is why abstract classes often sit at the top of an inheritance hierarchy.
4.5.2.2No object can be created from an abstract class
The most striking rule about an abstract class is that no object can be created from it with new. Of the three lines below, the first does not compile and the other two do:
Shape s1 = new Shape("?"); // ERROR
Shape s2 = new Square(3); // OK: the variable type may be abstract
Shape[] arr = new Shape[3]; // OK: the array holds only referencesAbstractNew.java:8: error: Shape is abstract; cannot be instantiated
Shape s1 = new Shape("?");
^
1 errorThe ban is not arbitrary. The area() method of Shape has no body. If new Shape("?") were allowed, there would be no code to run in the call s1.area(). The compiler prevents this up front: an object with a missing body is never created.
The name of an abstract class, however, can be used freely as a reference type. A variable, a parameter, an array element and a return type can be Shape. The Shape s2 = new Square(3); on the second line is exactly the notation abstraction wants: the type of the variable is the concept, the class of the object is the detail. The third line often surprises students. new Shape[3] does not create a Shape object; it creates an array with three slots, and each slot starts as null. The array object holds references, not objects of the abstract class. This is clearly seen when the lines are run:
abstract class Shape {
private String name;
Shape(String name) { this.name = name; }
abstract double area();
}
class Square extends Shape {
private double side;
Square(double side) { super("Square"); this.side = side; }
double area() { return side * side; }
}
public class D05 {
public static void main(String[] args) {
Shape s2 = new Square(3); // OK: the variable type may be abstract
Shape[] arr = new Shape[3]; // OK: the array holds only references
System.out.println(s2.area());
System.out.println(arr.length + " " + arr[0]);
}
}9.0
3 nullA class cannot be both abstract and final. final forbids extending the class; abstract requires it to be extended, because an object can be created only from a subclass. The two modifiers contradict each other:
abstract final class Shape { }
public class AbstractFinal { }AbstractFinal.java:1: error: illegal combination of modifiers: abstract and final
abstract final class Shape { }
^
1 error4.5.2.3Abstract methods and their rules
An abstract method is a method defined without a body, with only its signature. It contains no braces and ends with a semicolon. Every concrete subclass must implement it, that is, write its body.
public abstract void draw();A class that has an abstract method must itself be abstract. In the two files below, Shape declares the abstract method draw() and Circle implements it:
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");
}
}Drawing a circleThe call new Circle().draw(); runs the body that Circle wrote. Implementing an abstract method follows the same rules as overriding an ordinary method. The signature (name and parameter list) must be exactly the same, and access must not be narrowed. Since the method in the superclass is public, the one in Circle is public too.
The rules about abstract methods fit in a short table. Table 4.5.1 gives correct and wrong forms together with real compiler messages.
| Written | Result |
|---|---|
abstract void draw(); (in an abstract class) | Correct |
abstract void draw() { } | abstract methods cannot have a body |
class Shape { abstract void draw(); } | Shape t not abstract and does not override abstract method draw() in Shape |
class Circle extends Shape { } (no draw) | Circle t not abstract and does not override abstract method draw() in Shape |
private abstract, static abstract, final abstract | illegal combination of modifiers: abstract and private (the same message for static and final) |
abstract class Circle extends Shape { } | Correct: an abstract subclass can leave the implementation to its own subclasses |
abstract class A { void f() { } } | Correct: an abstract class with no abstract methods can also be written; still, new A() cannot be done |
The message in the third row of the table looks odd at first sight: “Shape is not abstract and does not override abstract method draw() in Shape.” The compiler gives every class with an abstract method two options: either the class becomes abstract or it writes the method. A class not writing the method it declared itself produces the same message. The fourth row is the same rule in the subclass.
Why are the three modifiers in the fifth row forbidden? All three prevent the method from being overridden in a subclass. A private method is invisible to the subclass. A static method is tied to the class, not to the object, and does not take part in dynamic binding. A final method cannot be overridden. An abstract method exists only to be overridden. The static version of the message looks like this:
abstract class Shape {
static abstract void draw();
}
public class StaticAbstract { }StaticAbstract.java:2: error: illegal combination of modifiers: abstract and static
static abstract void draw();
^
1 errorThe last two rows show two allowed but little-known cases. A subclass of an abstract class can be abstract too; then the obligation to write the method passes to a lower generation. A class with no abstract method at all can also be marked abstract. This is the way of saying “do not create objects directly from this class, only extend it”. In the program below both cases compile and run:
abstract class Shape { abstract void draw(); }
abstract class Circle extends Shape { }
abstract class A { void f() { System.out.println("f"); } }
class Circle extends Circle { void draw() { System.out.println("Drawing a circle"); } }
public class Main {
public static void main(String[] args) {
Shape s = new Circle();
s.draw();
A a = new A() { }; // anonymous concrete subclass
a.f();
}
}Drawing a circle
fSince AbstractCircle stays abstract, it has not written draw(); the concrete Circle that extends it writes it. The expression new A() { } creates not an object of A but an object of an anonymous subclass that extends A. This notation is called an anonymous class.
Writing the signature of an abstract method wrongly. If the abstract method in Shape is double area() and the subclass writes double Area() or double area(int x), it is a new method. The abstract area() is still missing and the compiler rejects the class:
WrongSignature.java:2: error: Square is not abstract and does not override abstract method area() in Shape
class Square extends Shape {
^
1 errorThe message shows not the place of the mistake but its consequence; the typo may go unnoticed. If @Override is written above the method, the compiler states the real error directly: method does not override or implement a method from a supertype.
4.5.2.4The constructor of an abstract class
If no object can be created from an abstract class, what is its constructor for? The answer lies in how a subclass object is built. When a Square object is created, the part of the object that comes from Shape must be built too: the name field must be given a value. The constructor of Shape does this job and the subclass calls it with super(...). In the program below the Shape constructor also prints a message, so the output shows when the call is made.
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());Square created
9.0Table 4.5.2 gives the ten steps of the program. The line numbers are the lines of the code above. The “Call stack” column lists the frames on the stack at that moment from left to right, from the bottom to the top.
| Step | Line | Call stack | Variables | New output |
|---|---|---|---|---|
| 1 | 18: Shape s = new Square(3); | main() | s=— | — |
| 2 | 11: Square(double side) { | main() → Square(3) | side=3.0 | — |
| 3 | 12: super("Square"); | main() → Square(3) | side=3.0 | — |
| 4 | 3: Shape(String name) { | main() → Square(3) → Shape("Square") | name="Square" | — |
| 5 | 4: this.name = name; | main() → Square(3) → Shape("Square") | name="Square" | — |
| 6 | 5: System.out.println(name + " created"); | main() → Square(3) → Shape("Square") | name="Square" | Square created |
| 7 | 13: this.side = side; | main() → Square(3) | side=3.0 | — |
| 8 | 18: Shape s = new Square(3); | main() | s=→ Square | — |
| 9 | 15: double area() { return side * side; } | main() → Square.area() | side=3.0 | — |
| 10 | 19: System.out.println(s.area()); | main() | s=→ Square | 9.0 |
In the first step, new Square(3) reserves space for a Square object on the heap. The object has two fields: name from Shape and side, which belongs to Square. Both get their default values: null and 0.0. In the second step the constructor of Square starts to run. The argument is the int 3 and the parameter is a double; the value is widened automatically to 3.0.
new has allocated the object, and the fields hold default values. In the middle the Shape constructor has built the part of the object that comes from Shape: name = "Square". On the right the Square constructor is finished too and the reference has been assigned to s.In the third step the first line of the Square constructor, super("Square"), runs and the superclass constructor is called. In the fourth step a Shape("Square") frame is added to the stack. There is a very important detail here: a separate Shape object is not created. There is still a single object on the heap. The Shape constructor builds the part of the same object that comes from Shape. In the fifth step this.name = name sets the field of this part to "Square", in the sixth step the message is printed and the frame of Shape leaves the stack.
In the seventh step control returns to the constructor of Square and this.side = side runs. The object is now completely built. In the eighth step the reference that is the value of the new expression is assigned to s. The type of the variable is the abstract Shape, and the object it points to is a Square. The drawing on the right of Figure 4.5.3 shows this moment.
The ninth step does the real work of abstraction. When s.area() is compiled, the compiler looks only at Shape: Shape has a method called area() that returns double, so the call is valid. At run time the JVM looks at the actual class of the object and runs Square.area(): 3.0 · 3.0 = 9.0. In the tenth step this value is printed.
The order of the constructor chain is the same as in inheritance: first the superclass constructor, then the subclass's. The abstract class does not change this order; it only forbids creating an object directly from the top link of the chain. Since Shape has no no-argument constructor, the constructor of Square must write super("Square"). Had it not, the compiler would insert super() itself and report an error because it cannot find the no-argument constructor.
4.5.2.5The template method
A concrete method of an abstract class can call an abstract method of the same class. At first hearing this seems contradictory: how can a method without a body be called? The call compiles, because the signature of the method is known. At run time this always points to an object of a concrete subclass, and in that object's class the method has a body. The Beverage class below fixes the order in which a beverage is prepared:
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();Water boiled
Tea brewed
Servedprepare() calls three steps in order: boiling the water, brewing, serving. Boiling water is the same for every beverage; boilWater() is written concretely in Beverage. Brewing differs by beverage; brew() is abstract and Tea fills it in with its own body. prepare() is final: subclasses cannot override it, that is, they cannot disturb the order of preparation.
| Step | Line | Call stack | Variables | New output |
|---|---|---|---|---|
| 1 | 18: Beverage i = new Tea(); | main() | i=→ Tea | — |
| 2 | 2: final void prepare() { | main() → prepare() | this=→ Tea | — |
| 3 | 3: boilWater(); | main() → prepare() | this=→ Tea | — |
| 4 | 8: System.out.println("Water boiled"); | main() → prepare() → boilWater() | this=→ Tea | Water boiled |
| 5 | 4: brew(); | main() → prepare() | this=→ Tea | — |
| 6 | 14: System.out.println("Tea brewed"); | main() → prepare() → Tea.brew() | this=→ Tea | Tea brewed |
| 7 | 5: System.out.println("Served"); | main() → prepare() | this=→ Tea | Served |
| 8 | 19: i.prepare(); | main() | i=→ Tea | — |
Table 4.5.3 gives the call step by step. In the first step the type of the variable is the abstract Beverage and its object is a Tea. Tea is concrete because it implements the only abstract method brew(), and its object can be created. In the second step i.prepare() is called. Tea has no prepare(); the inherited version from Beverage runs. In the third and fourth steps boilWater(), that is this.boilWater(), is called, and the concrete body in Beverage prints “Water boiled”.
prepare() the call to brew() has been reached; Beverage has no body for this method. The moment on the right: since this is a Tea object, the call goes to Tea.brew().The fifth step is the critical moment. prepare() calls brew(). Beverage has no body for this method, but this is a Tea object. Dynamic binding directs the call to Tea.brew() and in the sixth step “Tea brewed” is printed (Figure 4.5.4). The code in the abstract class has called the code of a subclass that did not yet exist when the abstract class was written. In the seventh step the serving message is printed.
The template method is a design that defines the skeleton of an algorithm in the superclass and leaves the varying steps to the subclasses. The method that builds the skeleton is usually final; the varying steps are abstract methods.
The strength of the template method shows when a new beverage is added. A Coffee class writes only brew(); it takes the water-boiling and serving steps, together with their order, ready-made:
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");
}
}
class Coffee extends Beverage {
void brew() {
System.out.println("Coffee filtered");
}
}
public class Main {
public static void main(String[] args) {
Beverage[] order = { new Tea(), new Coffee() };
for (Beverage i : order) {
i.prepare();
}
}
}Water boiled
Tea brewed
Served
Water boiled
Coffee filtered
ServedThe loop calls the same prepare() on both objects. The skeleton does not change; the middle line runs the method of each object's own class. Since the order of preparation is written in a single place, adding a “warm the cup” step before serving, for example, changes all beverages together.
Trying to override a final template method in a subclass. The template method is written final to protect the skeleton. If a subclass wants to rewrite it, the compiler rejects it:
FinalPrepare.java:7: error: prepare() in Tea cannot override prepare() in Beverage
void prepare() { }
^
overridden method is final
1 errorIf part of the order really must be variable, the template is not broken. A “hook” method with a body that can be overridden is added to the skeleton (for example boolean addMilk() { return false; }).
4.5.3Interfaces
An abstract class works well as the common ancestor of related classes. A square and a circle are both shapes. But some things in common do not come from kinship. A bird, an airplane and a drone can fly; the three have no common ancestor, and should not have one. A duck both flies and swims; since it has a single superclass, it cannot derive from two separate abstract classes at the same time. Java offers a second tool of abstraction for this need: the interface.
4.5.3.1An interface is a contract
An interface is a type that specifies the methods classes must implement. It is defined with the interface keyword. A class implements an interface with implements, that is, it writes the bodies of the abstract methods in the interface.
An interface is a contract. It guarantees that every class implementing it will offer certain methods. It is the meeting point between two pieces of software: the using side knows only the interface and does not know the class behind the contract. Figure 4.5.5 draws this relationship.
GeometricShape interface and its draw() method. Square and Circle implement the same contract (dashed arrows).An everyday analogy describes the interface well: the socket and the plug. The socket is a contract. Whatever device is plugged in, it gives the same voltage. Both an iron and a computer obey the standard of the socket. The grid does not know the inside of the device, and the device does not know how the grid is built. Making a new device does not require changing the grid; following the standard is enough.
The rules of an interface differ from those of a class:
- Methods in an interface are
public, whether or notpublicis written. - A method that is not
static,defaultorprivateisabstractby itself. - Only
public static finalconstants can be fields. There are no instance fields and no constructors.
The difference between an abstract class and an interface can be summed up with two relationship names. An abstract class establishes an “is-a” relationship: a square is a shape. An interface defines a “can-do” ability: a duck can fly, a duck can swim.
4.5.3.2Defining an interface
Below, on the left is the interface the programmer wrote, on the right how the compiler sees it. The compiler adds the modifiers that were not written:
public interface GeometricShape {
// abstract method (public abstract)
void draw();
// constant (public static final)
int SIDES = 4;
}public interface GeometricShape {
public abstract void draw();
public static final int SIDES = 4;
}The line void draw(); is read as public abstract void draw();. The line int SIDES = 4; is a public static final constant. Constants are reached with the interface name: GeometricShape.SIDES gives 4. Constant names are traditionally written in UPPER_CASE. These implicit modifiers have three consequences, and the compiler checks all three.
First, giving a value to a constant in an interface is mandatory. A final field without a value cannot get one later either, because an interface has no constructor:
interface GeometricShape {
int value;
}
public class FinalNoValue { }FinalNoValue.java:2: error: = expected
int value;
^
1 errorSecond, the constant cannot be changed. A final field cannot be assigned a second time:
interface GeometricShape {
void draw();
int SIDES = 4;
}
public class AssignFinal {
public static void main(String[] args) {
GeometricShape.SIDES = 5;
}
}AssignFinal.java:7: error: cannot assign a value to static final variable SIDES
GeometricShape.SIDES = 5;
^
1 errorThird, an object cannot be created from an interface with new either. The message is the same as for an abstract class, because an interface is implicitly abstract too:
InterfaceNew.java:6: error: GeometricShape is abstract; cannot be instantiated
GeometricShape g = new GeometricShape();
^
1 errorAn interface having no instance fields means it cannot hold state. An interface cannot say “it stores a counter value”; it can only say “it offers a method called value()”. Storing the value is the job of the implementing class. If int value = 0; is written in an interface, it is not a counter but an immutable constant; a method that tries to increase it does not compile:
interface Counter {
int value = 0;
default void inc() { value++; }
}
public class InterfaceField { }InterfaceField.java:3: error: cannot assign a value to static final variable value
default void inc() { value++; }
^
1 error4.5.3.3Implementing an interface
A class implements an interface with the implements keyword. The class must write all the abstract methods of the interface or be abstract itself. The Square below writes draw(), the only abstract method of GeometricShape:
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);Drawing a square
4In the line GeometricShape g = new Square(); the type of the variable is the interface. A variable of an interface type can point to an object of any class implementing that interface. When g.draw() is compiled, the compiler looks at the interface; at run time the method of Square runs. The last line reaches the constant by the interface name and prints 4.
The implementing method must be public. A method in an interface is implicitly public and an overriding method cannot narrow access. If the class writes only void draw(), the method gets package access and the compiler sees this as weakening access:
interface GeometricShape {
void draw();
}
class Square implements GeometricShape {
void draw() { System.out.println("Drawing a square"); }
}
public class InterfaceWeaker { }InterfaceWeaker.java:5: error: draw() in Square cannot implement draw() in GeometricShape
void draw() { System.out.println("Drawing a square"); }
^
attempting to assign weaker access privileges; was public
1 errorIf the method is not written at all, the message is the same as for an abstract class; the only difference is the last word, which says in which type the missing method is declared:
InterfaceMissing.java:4: error: Square is not abstract and does not override abstract method draw() in GeometricShape
class Square implements GeometricShape { }
^
1 errorForgetting to write public on an interface method. Since public is not written in the interface, one thinks it need not be written in the class either. But the modifier in the interface is implicit, the one in the class is not. If no modifier is written in the class, the method gets package access and the message attempting to assign weaker access privileges; was public appears. An interface method is always written public in the class.
4.5.3.4One class, several interfaces
In Java a class can extend at most one superclass. In contrast, it can implement zero or more interfaces: implements A, B, …. If both are written, extends comes first, then implements. The Duck class below derives from Animal and takes on two abilities at once:
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"); }
}Duck extends Animal (solid line, hollow triangle) and implements the interfaces Flyable and Swimmable (dashed line).The constructor of Duck calls the constructor of Animal with super(name) and gets the name field from it. The methods fly() and swim() fulfill the contracts of the two interfaces; both are public. Figure 4.5.6 shows these three relationships with the two kinds of UML line: inheritance is drawn solid, implementing an interface dashed.
Writing two superclasses is a syntax error. The compiler expects a single name after extends; when it sees the comma, it expects the class body to begin:
class A { }
class B { }
class C extends A, B { }
public class TwoExtends { }TwoExtends.java:3: error: '{' expected
class C extends A, B { }
^
1 errorA Duck object can now be seen from three different types: Duck, Flyable and Swimmable. The program below holds a single object with three different references:
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);Donald is flying
Donald is swimming
Donald
true| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: Duck o = new Duck("Donald"); | o=→ Duck | — |
| 2 | 2: Flyable u = o; | o=→ Duck, u=→ Duck | — |
| 3 | 3: Swimmable y = o; | o=→ Duck, u=→ Duck, y=→ Duck | — |
| 4 | 4: u.fly(); | o=→ Duck, u=→ Duck, y=→ Duck | Donald is flying |
| 5 | 5: y.swim(); | o=→ Duck, u=→ Duck, y=→ Duck | Donald is swimming |
| 6 | 6: // u.swim(); compile error! | o=→ Duck, u=→ Duck, y=→ Duck | — |
| 7 | 7: System.out.println(o.name); | o=→ Duck, u=→ Duck, y=→ Duck | Donald |
| 8 | 8: System.out.println(u == o); | o=→ Duck, u=→ Duck, y=→ Duck | true |
The first three steps of Table 4.5.4 only assign. In the first step a single Duck object is created on the heap and o points to it. The Flyable u = o; in the second step does not copy the object; u points to the same object. Since a duck is a Flyable, this conversion is automatic, no explicit cast is needed. In the third step y points to the same object too. Now the single object is looked at from three different types (Figure 4.5.7).
o, u and y on the stack have different types, but all three point to the same Duck object on the heap.In the fourth step u.fly() is called. The type of u is Flyable, and from this type only fly() can be called. What runs is the object's own fly() method: “Donald is flying”. In the fifth step y.swim() runs; the type Swimmable knows swim(). The sixth step discusses the call in the comment line. Had u.swim() been written, the compiler would have rejected it:
RefType.java:10: error: cannot find symbol
u.swim();
^
symbol: method swim()
location: variable u of type Flyable
1 errorThe object has a swim() method, but the compiler looks not at the object but at the type of the reference. There is no swim() in the Flyable contract. The type of the reference decides which methods can be called; the class of the object decides which body runs. These two rules are the heart of polymorphism. In the seventh step o.name is read; since the type of o is Duck, every member, fields included, can be reached. In the last step u == o compares the two references. Since both point to the same object, the result is true.
4.5.3.5Inheritance between interfaces
An interface can extend another interface with extends. Multiple inheritance is allowed between interfaces: interface C extends A, B can be written. The extending interface inherits all the methods of the parent interface and adds new ones. The SquareShape below adds a special() to the draw() method of GeometricShape:
interface GeometricShape {
void draw();
int SIDES = 4;
}
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));
}
}
public class Main {
public static void main(String[] args) {
SquareShape k = new SpecialSquare();
k.draw();
k.special();
GeometricShape g = k; // can be assigned to the parent interface
System.out.println(g instanceof SquareShape);
}
}Drawing a special square
Diagonal: 1.4142135623730951
trueSquareShape interface extends GeometricShape; the class SpecialSquare implements SquareShape and writes both methods.SpecialSquare declares that it implements only SquareShape, but the contract covers both methods. Had one been missing, the class would not compile. A SpecialSquare object is indirectly a GeometricShape; that is why GeometricShape g = k; compiles without a cast (Figure 4.5.8). The last line of the program is an instanceof test and prints true: the reference of the parent interface type still points to the same object. The 1.4142135623730951 on the Diagonal line is the double representation of √2, the diagonal of a square with side 1.
4.5.3.6Programming to an interface type
The real strength of an interface is that it makes the using code independent of concrete classes. The way to do this is to write variable, parameter and return types as the interface instead of the concrete class. Consider the payment step of a shopping site. Payment can be made by card or by bank transfer; tomorrow cryptocurrency may be added too.
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);Card: 250.0 TL
Transfer: 125.0 TLThe method buy(PaymentMethod y, double total) does not know whether the payment is made by card or by transfer. It only says y.pay(total); the object does the rest. Figure 4.5.9 draws this dependency: the only arrow out of buy goes to the interface.
buy knows only the PaymentMethod interface. CreditCard, Transfer and the later-added Crypto implement the contract.| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 15: buy(new CreditCard(), 250.0); // main12: static void buy(PaymentMethod y, double total) { | y=→CreditCard #1, total=250.0 | — |
| 2 | 13: y.pay(total);3: public void pay(double amount) {4: System.out.println("Card: " + amount + " TL"); | this=→CreditCard #1, amount=250.0 | Card: 250.0 TL |
| 3 | 15: buy(new CreditCard(), 250.0); // main | — | — |
| 4 | 16: buy(new Transfer(), 120.0);12: static void buy(PaymentMethod y, double total) { | y=→Transfer #2, total=120.0 | — |
| 5 | 13: y.pay(total);8: public void pay(double amount) {9: System.out.println("Transfer: " + (amount + 5) + " TL"); | this=→Transfer #2, amount=120.0 | Transfer: 125.0 TL |
| 6 | 12: static void buy(PaymentMethod y, double total) {13: y.pay(total); | — | — |
In the first step of Table 4.5.5, line 15 calls buy with a new CreditCard object. The type of the parameter y is the interface; the object that arrives is a CreditCard. In the second step the y.pay(total) on line 13 is bound dynamically. Since the object is a card, CreditCard.pay() runs and “Card: 250.0 TL” is printed. In the third step the call ends. No reference to the card object remains; the garbage collector may remove it.
In the fourth step the same buy is called, this time with a Transfer object. In the fifth step the same line 13 runs Transfer.pay() this time. The transfer adds a fee of 5 TL: 120.0 + 5 = 125.0. The conclusion of the sixth step is important: buy worked with two different classes but knows the name of neither. It will not change when a new payment type is added either.
This independence is called loose coupling. It has two concrete benefits. First, a new payment type is added just by writing a class that implements the interface; buy and the code that calls it do not change at all. Second, the code is easy to test. Instead of a real bank, a fake class that implements the interface is given; this class does not draw any money, it only records how much payment has reached it:
interface PaymentMethod { void pay(double amount); }
class Crypto implements PaymentMethod {
public void pay(double amount) {
System.out.println("Crypto: " + amount / 2000 + " units");
}
}
class FakePayment implements PaymentMethod {
double received = 0;
public void pay(double amount) { received += amount; }
}
public class Main {
static void buy(PaymentMethod y, double total) {
y.pay(total);
}
public static void main(String[] args) {
buy(new Crypto(), 500.0);
FakePayment fake = new FakePayment();
buy(fake, 99.5);
buy(fake, 0.5);
System.out.println(fake.received);
}
}Crypto: 0.25 units
100.0Crypto is a payment type added later; it converts 500 TL into 0.25 units at a unit price of 2000 TL. FakePayment keeps the total of two payments: 99.5 + 0.5 = 100.0. That buy passes the right amount to the right object is thus tested without connecting to a real bank. Java's own library is written in the same fashion: in the line List<String> l = new ArrayList<>(); the type of the variable is the interface List. If the program later wants to use LinkedList instead of ArrayList, only this line changes.
4.5.4Lambda expressions
Most interfaces like PaymentMethod have a single abstract method. To implement such an interface one has to write a separate class, give it a name and place the body inside that class. If the class will be used only once, in one place, this ceremony is needlessly long. Lambda expressions, which came with Java 8, let you write a one-method behavior directly where it will be used.
4.5.4.1An anonymous function and its syntax
A lambda expression is an anonymous function made of a parameter list, an arrow (->) and a body: (ParameterList) -> Expression. An anonymous function represents the code itself directly, instead of a name.
The expression (int x, int y) -> x + y in Figure 4.5.10 takes two integers and returns their sum. The ordinary method that does the same job is:
static int add(int x, int y) {
return x + y;
}The differences between the two notations explain the short form of the lambda. A lambda has no name; the return type is not written, it is inferred from the type of the expression; in a single-expression body neither return nor braces are written. The syntax has a few forms:
- Parameter types are often not written; the compiler infers them from the context:
(x, y) -> x + y. - With a single parameter the parentheses are not needed either:
s -> s * 2. - A lambda with no parameters is written with empty parentheses:
() -> 4. - If the body consists of several statements, braces and
returnare needed:(a, b) -> { int s = a + b; return s; }.
The program below tries all of these forms with the same sum. Each lambda is assigned to a variable of an interface type. The type of a lambda is always such an interface.
import java.util.function.IntBinaryOperator;
public class Main {
static int add(int x, int y) {
return x + y;
}
public static void main(String[] args) {
IntBinaryOperator t1 = (int x, int y) -> x + y;
IntBinaryOperator t2 = (x, y) -> x + y;
IntBinaryOperator t3 = (a, b) -> { int s = a + b; return s; };
java.util.function.IntUnaryOperator twice = s -> s * 2;
System.out.println(add(5, 3) + " " + t1.applyAsInt(5, 3) + " " + t2.applyAsInt(5, 3) + " "
+ t3.applyAsInt(5, 3) + " " + twice.applyAsInt(21));
}
}8 8 8 8 42All four sums give 8; the one-parameter lambda twice doubles 21 to 42. The behavior is the same even though the notation changes.
4.5.4.2The functional interface
In Java every value has a type. What is the type of a lambda expression? Java answers this question without adding a new kind of type: a lambda is an object of an interface that has a single abstract method.
A functional interface is an interface with a single abstract method. A lambda expression can be assigned only to such a type. The lambda writes the body of that one method; the parameter and return types are inferred from the signature of the method.
@FunctionalInterface
interface Greeting {
void greet(String name);
}
Greeting s = name -> System.out.println("Hello " + name);
s.greet("Ayşe");Hello AyşeThe only abstract method of the Greeting interface is greet(String name). The lambda name -> System.out.println("Hello " + name) is the body of this method. The compiler infers the type of name as String from the method's parameter. The return type is void; the println call produces no value either. Figure 4.5.11 shows the match.
The @FunctionalInterface annotation is optional. If written, the compiler checks that the interface really is functional and does not allow a second abstract method to be added. Even without the annotation, every interface with a single abstract method can be a target for a lambda. The annotation is a safeguard against the programmer who changes the interface later. If someone accidentally adds a second method, all lambdas that use the interface break. The annotation catches this mistake in the interface itself.
The most important rule about lambdas is when they run. A lambda does not run when it is defined. The definition only creates an interface object and assigns it to the variable. The body runs when the method of the interface is called, that is on the line s.greet(...). To see this, let us add numbered messages to the program:
@FunctionalInterface
interface Greeting {
void greet(String name);
}
public class Main {
public static void main(String[] args) {
System.out.println("1: defining the lambda");
Greeting s = name -> System.out.println("3: Hello " + name);
System.out.println("2: not called yet");
s.greet("Ayşe");
s.greet("Ali");
}
}1: defining the lambda
2: not called yet
3: Hello Ayşe
3: Hello AliThe order in the output shows the rule clearly. The lambda was defined before message 2, but its body runs after message 2. Since the same lambda is called twice, its body runs twice too. A lambda is a behavior that is stored like a value, carried around and called when wanted.
Assigning a lambda to a type other than a functional interface is a compile error. Object is a class and has no single abstract method:
public class LambdaObject {
public static void main(String[] args) {
Object o = () -> System.out.println("?");
}
}LambdaObject.java:3: error: incompatible types: Object is not a functional interface
Object o = () -> System.out.println("?");
^
1 errorAn interface with two abstract methods cannot be a target of a lambda either. The compiler cannot know which method the lambda is the body of:
TwoAbstractLambda.java:7: error: incompatible types: Operation2 is not a functional interface
Operation2 i = (a, b) -> a + b;
^
multiple non-overriding abstract methods found in interface Operation2
1 error4.5.4.3Ready-made functional interfaces
There is no need to write a new interface for every lambda. The commonly used forms are ready in the package java.util.function. Table 4.5.6 gives the four most used.
| Interface | Input | Output | Method | Example use |
|---|---|---|---|---|
Consumer<T> | one value | none | accept | printing, storing |
Supplier<T> | none | one value | get | producing a value |
Function<T, R> | one value | one value | apply | converting |
Predicate<T> | one value | boolean | test | filtering, conditions |
The <T> and <T, R> beside the interface names are type parameters. Function<String, Integer> means a function that takes a String and returns an Integer. The types inside the angle brackets are the types of the input and the output.
Consumer<String> print = m -> System.out.println(m);
print.accept("Consumer ran");
Supplier<Integer> dice = () -> 4;
System.out.println(dice.get());
Function<String, Integer> length = m -> m.length();
System.out.println(length.apply("Giresun"));
Predicate<Integer> isPositive = x -> x > 0;
System.out.println(isPositive.test(-7));Consumer ran
4
7
falseThe program uses each of the four interfaces once. Consumer prints the message it receives and returns nothing. Supplier has no parameter; it produces 4 at every get() call. Function converts the string “Giresun” to its length: 7. Predicate answers the question “is it positive?” for −7: false. The method of each interface has a different name (accept, get, apply, test); the lambda does not know that name, the calling code does.
There are separate interfaces for primitive types too. IntBinaryOperator takes two int values and returns an int; its method is applyAsInt. IntUnaryOperator takes a single int. These interfaces remove the cost of boxing and unboxing.
4.5.4.4When does a lambda run?
Let us trace, in a list filtering example, how a lambda is stored like a value and called later. The lambda isEven says whether a number is even; the loop filters a list with this lambda.
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);[8, 12]| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: Predicate<Integer> isEven = x -> x % 2 == 0; | result=- | — |
| 2 | 2: List<Integer> numbers = Arrays.asList(3, 8, 5, 12); | result=- | — |
| 3 | 3: List<Integer> result = new ArrayList<>(); | result=[] | — |
| 4 | 4: for (int s : numbers) { | s=3, result=[] | — |
| 5 | 5: if (isEven.test(s)) { | s=3, test=false, result=[] | — |
| 6 | 4: for (int s : numbers) { | s=8, result=[] | — |
| 7 | 5: if (isEven.test(s)) { | s=8, test=true, result=[] | — |
| 8 | 6: result.add(s); | s=8, test=true, result=[8] | — |
| 9 | 4: for (int s : numbers) { | s=5, result=[8] | — |
| 10 | 5: if (isEven.test(s)) { | s=5, test=false, result=[8] | — |
| 11 | 4: for (int s : numbers) { | s=12, result=[8] | — |
| 12 | 5: if (isEven.test(s)) { | s=12, test=true, result=[8] | — |
| 13 | 6: result.add(s); | s=12, test=true, result=[8, 12] | — |
| 14 | 9: System.out.println(result); | result=[8, 12] | [8, 12] |
In the first step of Table 4.5.7 line 1 runs. The lambda is stored as a Predicate<Integer> object; its body has not run yet. isEven is a reference that points to this behavior. In the second step the list is built with the elements 3, 8, 5, 12, and in the third step the result list starts empty.
isEven.test(3) runs the body of the lambda and returns false. On the right the loop has finished: the result list holds 8 and 12.In the fourth step the loop takes the first element: s = 3. In the fifth step isEven.test(3) is called and the body of the lambda runs for the first time: 3 % 2 == 0 is false, the result is false (left of Figure 4.5.12). 3 is not added to the list. In the sixth and seventh steps the same work is done for 8: 8 % 2 == 0 is true. In the eighth step 8 is added to the result list. For 5 the condition is false, for 12 true; in the thirteenth step 12 is added too. In the last step the loop ends and [8, 12] is printed.
The lambda has run four times: once per test call. It never ran at the moment of definition. To verify this count, a counter can be added to the body of the lambda:
import java.util.*;
import java.util.function.*;
public class Main {
static int counter = 0;
public static void main(String[] args) {
Predicate<Integer> isEven = x -> { counter++; return x % 2 == 0; };
System.out.println("after definition: " + counter);
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 + " " + counter);
}
}after definition: 0
[8, 12] 4Right after the definition the counter is 0; after the loop it is 4. Note that the counter is a static field, not a local variable. The reason is that local variables cannot be modified from inside a lambda.
4.5.4.5Filtering and transforming with streams
The place where lambdas are used most is processing collections. The stream interface that came with Java 8 lets you pass a list through a series of operations, and each operation takes a lambda. The code below runs inside a 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 first two lines assign the sum lambda to the type IntBinaryOperator and call it with applyAsInt(5, 3): 8. Then a list of the numbers 1 to 7 is built. numbers.stream() produces a stream from the list. filter(s -> s % 2 == 0) keeps only the elements for which the lambda returns true, that is the even numbers. collect(Collectors.toList()) gathers the remaining elements in a new list: [2, 4, 6]. The lambda here has taken the place of an explicitly written loop; the Java library runs the loop inside filter.
The map(s -> s * s) on the last line transforms each element: every number is replaced by its square. The result is [1, 4, 9, 16, 25, 36, 49]. In short, filter reduces the number of elements but does not touch the values; map keeps the number of elements but changes the values. The .toList() on the last line came with Java 16. In older versions the same job is done with collect(Collectors.toList()). Here only the side of streams that takes a lambda is used.
4.5.4.6Lambda and anonymous class
Before lambdas, a one-method behavior was written with an anonymous class. An anonymous class is a nameless inner class whose single object is created where it is defined. The program below implements the same Runnable interface in two ways:
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
LambdaThe anonymous class written for r1 takes six lines: new Runnable(), braces, @Override, the full method signature and the body. The lambda written for r2 does the same job in a single expression. The compiler interprets the lambda as the body of the single method run() of Runnable. The run() calls of the two objects print the expected messages.
The brevity of the lambda has a price; three limits must be known. First, a lambda can be assigned only to a functional interface type. An anonymous class can also implement an interface with several methods or extend a class.
Second, the local variables a lambda uses must be final or effectively final. Effectively final means a variable not written final but never assigned a value after its initial value. The lambda below reads the local variable tax and adds 20% VAT to a price of 150 TL: 150 + 150 · 20 / 100 = 180.
int tax = 20;
Function<Integer, Integer> withTax =
price -> price + price * tax / 100;
System.out.println(withTax.apply(150)); // 180
tax = 18; // if added: compile errorIf the last line stays in a comment, the program compiles and prints 180. If that line is added, tax is no longer effectively final and the compiler points to the line where the lambda is:
LambdaFinal.java:6: error: local variables referenced from a lambda expression must be final or effectively final
price -> price + price * tax / 100;
^
1 errorThe reason for the rule is that a lambda can run later. A lambda can be called long after the method where it was defined, even after that method has ended. So it carries not the local variable itself but a copy of its value. Had the variable changed later, the value the lambda sees and the value the method sees would diverge. Java forbids this ambiguity up front. Fields do not fall under this rule; a lambda can read and change a field. This is why the counter in the counter example was written as a static field.
Third, the keyword this means something different. The this inside a lambda refers to the enclosing object, that is the object of the method that wrote the lambda. The this in an anonymous class refers to the anonymous object itself:
public class Main {
String name = "outer object";
void demo() {
Runnable lam = () -> System.out.println("lambda: " + this.name);
Runnable anon = new Runnable() {
String name = "anonymous object";
public void run() { System.out.println("anonymous: " + this.name); }
};
lam.run();
anon.run();
}
public static void main(String[] args) {
new Main().demo();
}
}lambda: outer object
anonymous: anonymous objectBoth bodies read this.name. Since the lambda has no object of its own, this is the outer Main object. The anonymous class is a separate object with its own name field.
4.5.4.7Uses
Lambda expressions shorten code markedly in three kinds of work:
- Collection operations. Filtering, sorting, mapping a list and doing something for each element (
filter,sort,map,forEach). - Thread management. Giving briefly the body of a job to be run in parallel.
- Readable code. Instead of defining a separate method or class for a small operation used in one place, writing the operation where it is used.
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 ranThe call names.sort(...) takes the sorting criterion as a lambda. (a, b) -> a.length() - b.length() returns the difference in length of two names. If the difference is negative, a comes first; if positive, b comes first; if zero, the two count as equal. “Ali” goes first because it has three letters. “Zeynep” and “Mehmet” have six letters each; Java's list sort keeps the original order of equal elements, so “Zeynep” stays before “Mehmet”. Such a sort is called a stable sort.
forEach calls the given lambda for every element of the list and prints three greetings. The last two lines create a thread. The constructor of Thread expects a Runnable; () -> ... is a lambda with no parameters and becomes the body of run(). t.start() starts this body in a separate thread. The line t.join() was added to the program that was run; it makes main wait for the thread to finish. In this program the last message is printed last anyway, because there is no other work before it.
Changing the sorting criterion means only changing the lambda. The program below sorts the same list by three criteria. Comparator.comparing(String::length) is the ready-made way of saying “by length”; the notation String::length is a shorthand (a method reference) for the lambda s -> s.length(), which only calls one method.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Zeynep", "Ali", "Mehmet"));
names.sort(Comparator.comparing(String::length));
System.out.println(names);
names.sort((a, b) -> b.length() - a.length());
System.out.println(names);
names.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(names);
}
}[Ali, Zeynep, Mehmet]
[Zeynep, Mehmet, Ali]
[Ali, Mehmet, Zeynep]The first line sorts from short to long, the second from long to short; in the second too, elements of equal length keep their original order. The third line looks at alphabetical order when lengths are equal and puts “Mehmet” before “Zeynep”.
4.5.5Methods with bodies in interfaces
Until Java 8 an interface could contain only abstract methods and constants. This rigidity caused a big problem. New methods that work with lambdas (forEach, removeIf, stream) were to be added to Java's own Collection and List interfaces. Adding a new abstract method to an interface breaks all classes that implement it: every list class in the world would suddenly stop compiling. The solution was to allow methods with bodies in interfaces. Today an interface can contain three kinds of method with a body: default (default), static and private.
4.5.5.1Default methods
A default method is a method written in an interface with the default keyword and a body (Java 8+). A class implementing the interface inherits it ready-made; it overrides it if it wishes.
The Collection interface below has three abstract methods and one default method. This Collection is a small interface we wrote ourselves; it should not be confused with java.util.Collection.
interface Collection {
void add(Object o);
void remove(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 void remove(Object o) { count--; }
public int size() { return count; }
// no isEmpty() written: the default version is used
}
// in main:
Cart cart = new Cart();
System.out.println(cart.isEmpty());
cart.add("apple");
cart.add("pear");
System.out.println(cart.size() + " " + cart.isEmpty());true
2 falseisEmpty() calls the abstract size(). Whether a collection is empty is whether its element count is zero; this information is computed in the same way for every collection. Which size() runs is determined by the object. Cart has written only the three abstract methods; it takes isEmpty() ready-made. On an empty cart true is printed, and after two elements are added 2 false.
The way a default method works is similar to a template method: the body in the interface calls the method of a class that has not been written yet. Let us trace a short version step by step.
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());true
false| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 13: Collection c = new Cart(); // main | c=→Cart #1, count=0 | — |
| 2 | 14: System.out.println(c.isEmpty());4: default boolean isEmpty() { | c=→Cart #1 | — |
| 3 | 5: return size() == 0;11: public int size() { return count; } | size()=0 | — |
| 4 | 5: return size() == 0; | size()=0, result=true | true |
| 5 | 15: c.add("apple");10: public void add(Object o) { count++; } | count=1 | — |
| 6 | 16: System.out.println(c.isEmpty());5: return size() == 0;11: public int size() { return count; } | size()=1, result=false | false |
In the first step of Table 4.5.8 a Cart object is created and assigned to c, which has the interface type. Cart has written only two abstract methods, add and size. In the second step c.isEmpty() is called. The JVM first looks for the method in the class of the object; Cart has no isEmpty(). The search goes up to the interface and the default body there runs.
Cart has no isEmpty(), the default version in the interface is chosen. On the right, the size() that the default body calls is bound dynamically to Cart.size().In the third step the default body calls size(). This call means this.size(), and this is a Cart; the object decides which body runs: Cart.size() returns 0 (Figure 4.5.13). In the fourth step the comparison 0 == 0 gives true and it is printed. In the fifth step c.add("apple") runs the version of Cart and count becomes 1. In the sixth step the same default body sees 1 this time and returns false.
The lesson of the example is this: a default method added after the interface was written reaches old classes too, without breaking them. Even if isEmpty() had not been known at all when Cart was written, Cart objects would start to use it the day it is added to the interface as a default method. Java's forEach and removeIf methods were added to all list classes this way.
There is one more precedence rule for default methods: the class wins. If a class receives a method with the same signature both from its superclass and from the default method of an interface, the version in the superclass is chosen:
class Machine {
public void work() { System.out.println("Machine is working"); }
}
interface Printer {
default void work() { System.out.println("Printing"); }
}
class Photocopy extends Machine implements Printer { }
public class Main {
public static void main(String[] args) {
Printer y = new Photocopy();
y.work();
}
}Machine is workingPhotocopy has not written work(). It could take the method both from Machine and from the default body of Printer. The rule puts the class hierarchy first and “Machine is working” is printed. A default method does not override behavior already present in the class; it only completes what is missing.
4.5.5.2static methods
static methods can also be written in an interface (Java 8+). These methods are not tied to an object; they keep helper functions related to the interface together. They are called only with the name of the interface.
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));12.566370614359172
9.0
10.0
24.0The Geometry interface gathers four geometric computations. The area of a circle with radius 2 is π · 2 · 2 = 12.566370614359172. The area of a square with side 3 is 9.0, and the perimeter of a square with side 2.5 is 10.0. The volume of a box of size 2 × 3 × 4 is 24.0. The calls have the form Geometry.circleArea(2).
The static methods of an interface are not inherited by the implementing class. This differs from static methods in classes; a static method of a class can also be called with the name of a subclass. Even if Circle implements Geometry, Circle.squareArea(2) does not compile:
interface Geometry {
static double squareArea(double s) { return s * s; }
}
class Circle implements Geometry { }
public class StaticInheritance {
public static void main(String[] args) {
System.out.println(Circle.squareArea(2));
}
}StaticInheritance.java:7: error: cannot find symbol
System.out.println(Circle.squareArea(2));
^
symbol: method squareArea(int)
location: class Circle
1 errorThe reason for the rule is multiple inheritance. A class can implement many interfaces; if two interfaces had a static method with the same name, which would Circle.squareArea refer to? By always requiring the interface name for the call, Java removes this question.
The constant π used in the area of the circle is in the class Math and must be written with its full name. If only PI is written, the compiler looks for it in the interface and cannot find it:
PIOnly.java:2: error: cannot find symbol
static double circleArea(double r) { return PI * r * r; }
^
symbol: variable PI
location: interface Geometry
1 error4.5.5.3Default conflicts
When a class implements two interfaces and both bring a default method with the same signature, the class cannot know which to take. In this case Java does not guess; it forces the class to write the method itself, that is, to override it. The version of the wanted interface can be called with the notation 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();
}
}Hello
WelcomeClerk wants to use both greetings. Greeter.super.greet() prints “Hello”, and Welcomer.super.greet() prints “Welcome”. The interface name before super says whose default body is wanted. Had greet() not been written at all in Clerk, the class would not compile:
DefaultConflict.java:7: error: types Greeter and Welcomer are incompatible;
class Clerk implements Greeter, Welcomer { }
^
class Clerk inherits unrelated defaults for greet() from types Greeter and Welcomer
1 errorThe office machine example below shows the same situation step by step. The machine is both a printer and a scanner, and both interfaces bring a default body for work().
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();Scanning
Printing
Copy ready| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 14: Printer y = new OfficeMachine(); // main | y=→OfficeMachine #1 (type: Printer) | — |
| 2 | 15: y.work();8: public void work() { | this=→OfficeMachine #1 | — |
| 3 | 9: Scanner.super.work();5: default void work() { System.out.println("Scanning"); } | this=→OfficeMachine #1 | Scanning |
| 4 | 10: Printer.super.work();2: default void work() { System.out.println("Printing"); } | this=→OfficeMachine #1 | Printing |
| 5 | 11: System.out.println("Copy ready"); | this=→OfficeMachine #1 | Copy ready |
| 6 | 15: y.work(); | y=→OfficeMachine #1 | — |
Scanner.super.work() calls the body of the named interface.In the first step of Table 4.5.9 an OfficeMachine object is created and assigned to y of type Printer. In the second step y.work() is called. The type of the reference is Printer but the object is an OfficeMachine; the class's own work() runs. That the reference is a Printer does not mean the default body of Printer will be chosen; the version the class wrote always comes first.
In the third step Scanner.super.work() calls the default body of Scanner and “Scanning” is printed. In the fourth step it is the turn of Printer's: “Printing”. The class decides which versions are used in which order. In the fifth step the class makes its own addition: “Copy ready”. The result is a new behavior that combines two abilities. In the sixth step the call ends.
Trying to call the default method of an interface with super.method(). Plain super refers to the superclass, not an interface; to reach the body of an interface, the name of the interface is written: Scanner.super.work(). This notation is valid only for interfaces the class implements directly.
4.5.5.4private methods
As default methods multiply, shared code accumulates among them. This code needs to be moved to a separate method, but if the method is default, it is opened to every class that implements the interface. Java 9 solves this problem with private interface methods.
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"; }
}Document: Midterm resultsprivate methods share the common helper code of default and static methods without opening it to the outside. They have bodies and can be called only from inside the interface. The flow is this: print() (default) first calls title() (private), then content() (the abstract method that Report implements) and combines the two (Figure 4.5.15).
print() calls title(), which is visible only inside the interface, and the content() that Report wrote; the result is “Document: Midterm results”.The implementing class cannot see the private method. If title() is called from inside Report, the compiler looks for the method in Report and cannot find it:
PrivateCall.java:11: error: cannot find symbol
public String content() { return title(); }
^
symbol: method title()
location: class Report
1 error4.5.5.5Summary of interface members
All the members an interface can contain, their implicit modifiers and the Java version they came with are gathered in Table 4.5.10.
| 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() {…} | only inside the interface | yes | 9 |
| Instance field, constructor | — | Not allowed: an interface has no objects and cannot hold state | ||
The rule for the implementing class is short: all abstract methods of the interface are written public. Writing the default methods is optional; static and private methods are not inherited anyway. The ban in the last row of the table shows up in the compiler too. If a constructor is written inside an interface, the compiler does not recognize it as a constructor; it reads it as a method without a return type and expects a type name:
interface Counter {
Counter() { }
}
public class InterfaceCtor { }InterfaceCtor.java:2: error: <identifier> expected
Counter() { }
^
1 error4.5.6Sealed types
When a class or interface is written, by default anyone can extend or implement it. This openness is often useful, but sometimes it does not reflect the truth of the design. A traffic light can only be red, yellow or green; a payment can only be by card, transfer or cash. In such a hierarchy, adding a new subtype unnoticed leaves all the code that handles it incomplete. Sealing, which came with Java 17, makes it possible to close the list of subtypes.
A sealed class or interface is a type declared with the sealed keyword (Java 17+). Only the subtypes named in its permits list can extend or implement this type.
Every permitted subtype must choose how the hierarchy continues after it. There are three options:
final: the hierarchy ends here; no class can be derived from this type.sealed: the type is restricted again; it gives its ownpermitslist.non-sealed: the restriction is lifted; anyone can extend this type.
The real benefit of sealing is that the compiler knows all the subtypes. Such a hierarchy is called a closed hierarchy. In the example below the Animal interface permits only Cat and Dog:
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");
}
}Animal interface permits only the types Cat (final) and Dog (non-sealed). Kangal extends Dog freely; Bird is not permitted.Since Cat is final, that branch of the hierarchy is closed. Dog is non-sealed; so Kangal extends Dog without any permission (Figure 4.5.16). Kangal is indirectly an Animal, but not a direct subtype of Animal; so it need not be in the permits list.
What a sealed type gives the compiler shows when it is used with switch. In Java 21 a switch can branch on the type of an object, and the compiler checks whether all subtypes are handled:
// 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));
}Cat walks silently
cat
Dog runs
dog
Kangal guards the flock
dogThe switch in the method kind has no default branch. The compiler knows that an Animal can only be a Cat or a Dog; so it can prove that the two branches cover every case. The branch case Cat k catches the object under the name k if it is a Cat. The third object in the loop is a Kangal; move() runs its own version, while the switch recognizes it as a Dog and returns “dog”.
The value of this check shows when the hierarchy changes. If a new subtype is added to the permits list, every switch that does not handle it stops compiling. The switch below handles only Cat:
sealed interface Animal permits Cat, Dog { }
final class Cat implements Animal { }
final class Dog implements Animal { }
public class SwitchMissing {
static String kind(Animal h) {
return switch (h) {
case Cat k -> "cat";
};
}
}SwitchMissing.java:6: error: the switch expression does not cover all possible input values
return switch (h) {
^
1 errorHad a default branch been written, this help would be lost: the new type would silently fall into default. Not writing default in a sealed hierarchy is therefore a deliberate choice.
Violating the sealing rules is a compile error. A class not in the permits list cannot implement the sealed type:
sealed interface Animal permits Cat, Dog { }
final class Cat implements Animal { }
final class Dog implements Animal { }
final class Bird implements Animal { }
public class SealedNotPermitted { }SealedNotPermitted.java:4: error: class is not allowed to extend sealed class: Animal (as it is not listed in its 'permits' clause)
final class Bird implements Animal { }
^
1 errorThe phrase “sealed class” in the message is used for interfaces too. If a permitted subtype does not choose one of the three modifiers, the compiler stops too:
sealed interface Animal permits Cat, Dog { }
class Cat implements Animal { }
final class Dog implements Animal { }
public class SealedNoModifier { }SealedNoModifier.java:2: error: sealed, non-sealed or final modifiers expected
class Cat implements Animal { }
^
1 errorThe three fixes for this error are three different design decisions. final class Cat ends the hierarchy there. sealed class Cat permits Tabby restricts again; then Tabby must choose a modifier too. non-sealed class Cat opens Cat to everyone.
4.5.7Interface or abstract class?
An abstract class and an interface are similar: no object can be created from either, both are used as reference types, and both make subtypes write methods. Since interfaces also carry methods with bodies after Java 8, the difference has become even finer. Table 4.5.11 puts the two tools side by side.
| Property | Interface | Abstract class |
|---|---|---|
| Definition / 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 kind of field (instance fields included) |
| Constructor | None | May have one; the 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 class derives from only one class |
| Purpose | A common ability for unrelated classes (“can do”) | Grouping closely related classes with common fields (“is a”) |
| Objects | No object can be created from either with new; both are used as reference types | |
The most decisive rows of the table are “Fields” and “Inheritance”. An abstract class carries state but has a single parent. An interface carries no state but a class can take as many interfaces as it wants. The choice is mostly made by these two criteria.
An abstract class is appropriate when:
- The subclasses are close relatives:
SquareandCircleare both aShape. - Common fields and a constructor are needed (like
name). - Part of the common code is ready-made (like a template method).
An interface is appropriate when:
- The same ability is to be given to unrelated classes:
Bird,AirplaneandDroneare allFlyable. - Several abilities are to be given to one class.
- A contract is to be established between the using code and the implementing code. Such a contract is called an API (application programming interface).
Often the two are used together:
abstract class Animal implements Noisy { … }
class Duck extends Animal implements Flyable, Swimmable { … }In this notation the abstract class Animal carries kinship and common state; the interfaces Noisy, Flyable and Swimmable add abilities. A Duck is an Animal, and can both fly and swim.
The reason Java does not allow multiple inheritance of classes is that, when two superclasses define the same field or method differently, it becomes unclear which one applies. This problem is called the diamond problem because of the shape of the drawing in which two superclasses come from a common ancestor. Since interfaces carry no state, most of the problem disappears. The only remaining ambiguity is the conflict of two default methods, and the compiler makes the class resolve that too.
Let us follow the decision process with an example. We are to design a Vehicle with a plate number and a constructor and an abstract method int wheelCount(), and a Chargeable with the constant CAPACITY = 100 and the method void charge(int percent). Vehicle has a field and a constructor; so it must be an abstract class. The ability to be charged can be given to an electric car, a phone and a drill alike; so Chargeable is an interface. The electric car uses both together:
abstract class Vehicle {
private final String plate;
Vehicle(String plate) { this.plate = plate; }
abstract int wheelCount();
String getPlate() { return plate; }
}
interface Chargeable {
int CAPACITY = 100;
void charge(int percent);
}
class ElectricCar extends Vehicle implements Chargeable {
private int load = 20;
ElectricCar(String plate) { super(plate); }
int wheelCount() { return 4; }
public void charge(int percent) {
load = Math.min(CAPACITY, load + percent);
}
int getLoad() { return load; }
}
public class Main {
public static void main(String[] args) {
ElectricCar e = new ElectricCar("28 ABC 61");
e.charge(50);
System.out.println(e.getLoad());
e.charge(50);
System.out.println(e.getLoad());
Vehicle t = e; Chargeable s = e;
System.out.println(t.wheelCount() + " " + (s == t));
}
}70
100
4 trueThe load starts at 20%. The first charge(50) makes it 70. In the second call 70 + 50 = 120 is computed, but Math.min(CAPACITY, …) limits the result to the capacity: 100. The constant CAPACITY comes from the interface by inheritance and is used by name inside the class. In the class declaration extends is written first, then implements, and charge is public. The object can be assigned to references of both type Vehicle and type Chargeable; since both references point to the same object, s == t gives true.
4.5.8Generics
Interfaces and abstract classes let code work with different classes. Generics take the same idea one step further: they let a class or a method work with different types, without losing type safety. The angle brackets in List<String> and Function<String, Integer> are the syntax of generics.
4.5.8.1Why generics?
Suppose we want to write a box class that can store a value of any type. Without generics, the only way that comes to mind is to use Object, the superclass of everything:
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 errorException in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
at Main.main(Main.java:12)This design has two flaws. First, reading a value from the box needs an explicit cast every time: (String) k.get(). The compiler does not know what is inside the box; it trusts the programmer's word. Second, when a value of the wrong type is put in, nobody objects. k.put(42) compiles, because 42 is boxed into an Integer object and every object is an Object. The error shows only while the program runs, on the line that tries to cast 42 to String: ClassCastException. The place where the mistake was made is far from the place where it is noticed.
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 compileGenericPut.java:10: error: incompatible types: int cannot be converted to String
k.put(42);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorIn the generic version the type of the box is a parameter: Box<T>. When Box<String> is written, String takes the place of T. put now accepts only String and get returns String. No cast is needed when reading. The wrong-typed k.put(42) is rejected at compile time, before the program runs.
The two gains of generics can be summed up this way. Type safety: a value of the wrong type is caught at compile time, not at run time. Reuse: a single implementation works for every type and no explicit cast is needed when reading.
4.5.8.2Generic class and generic method
Generics means writing classes and methods with one or several type parameters. A type parameter (T) is a placeholder that is replaced by the type argument (String, Integer …) given when the class or method is used.
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');Hello 43
Item: 3.14
Item: ABox<String> k1 and Box<Integer> k2 are two different uses of the same class. k2.get() returns an Integer; in the operation + 1 this value is unboxed and the result is 43. The empty pair of angle brackets in new Box<>() is called the diamond; the compiler infers the type from the declaration on the left.
print is a generic method. It declares the type parameter before the return type: static <T> void print(T item). The type is not written at the call; the compiler infers it from the argument. In print(3.14) T is Double, in print('A') it is Character.
A type argument must be a reference type. Box<int> does not compile; for primitive types the wrapper classes are used (Box<Integer>):
GenericInt.java:6: error: unexpected type
Box<int> k = new Box<>();
^
required: reference
found: int
1 errorType parameter names are traditionally a single capital letter: T type, E element, K key, V value, R result. The two letters in the name Function<T, R> describe the input type and the result type.
4.5.8.3Bounded type parameters
About a plain T the compiler knows nothing; on a value of type T only the methods of Object can be called. If we want to write a generic method that computes twice a number, we have to say that T is a number.
A bounded type parameter is a type parameter written in the form <T extends Parent>. T can be only Parent or a subtype of it. Parent is called the upper bound. In return the method body can use the methods of Parent.
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 compile42.0
3.0Thanks to the bound <T extends Number>, the call x.doubleValue() compiles; this method is in the class Number and exists in all subclasses such as Integer and Double. For 21 T = Integer is inferred, for 1.5 T = Double, and the results are 42.0 and 3.0. On the third line "ten" is a String and not a subtype of Number; the compiler rejects the call:
TwiceTen.java:6: error: method twice in class TwiceTen cannot be applied to given types;
System.out.println(twice("on"));
^
required: T
found: String
reason: inference variable T has incompatible bounds
upper bounds: Number
lower bounds: String
where T is a type-variable:
T extends Number declared in method <T>twice(T)
1 errorThe last part of the message shows the compiler's reasoning: for T the upper bound is Number and the lower bound coming from the argument is String. No type satisfies both.
An interface can be a bound too; even when the bound is an interface, extends is written, not implements. The method below finds the largest element in any comparable type (Integer, String …). The bound T extends Comparable<T> guarantees that every value of type T can be compared with another T by the compareTo method.
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", "kiwi", "pear"};
System.out.println(max(numbers));
System.out.println(max(fruits));12
kiwi
1 -1 6 -10The compareTo contract is this: if a.compareTo(b) is negative, a is smaller; if zero, equal; if positive, larger. The third line of the output was added to the program to verify the four compareTo values used in the trace.
| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 11: Integer[] numbers = {7, 12, 5};12: String[] fruits = {"elderberry", "kiwi", "apricot"}; | numbers=[7, 12, 5], fruits=[elderberry, kiwi, apricot] | — |
| 2 | 13: System.out.println(max(numbers));1: static <T extends Comparable<T>> T max(T[] arr) {2: T best = arr[0]; | T=Integer, best=7 | — |
| 3 | 3: for (int i = 1; i < arr.length; i++) {4: if (arr[i].compareTo(best) > 0) {5: best = arr[i]; | T=Integer, i=1, compareTo=1, best=12 | — |
| 4 | 3: for (int i = 1; i < arr.length; i++) {4: if (arr[i].compareTo(best) > 0) { | T=Integer, i=2, compareTo=-1, best=12 | — |
| 5 | 8: return best;13: System.out.println(max(numbers)); | T=Integer, best=12 | 12 |
| 6 | 14: System.out.println(max(fruits));2: T best = arr[0]; | T=String, best="elderberry" | — |
| 7 | 3: for (int i = 1; i < arr.length; i++) {4: if (arr[i].compareTo(best) > 0) {5: best = arr[i]; | T=String, i=1, compareTo=6, best="kiwi" | — |
| 8 | 3: for (int i = 1; i < arr.length; i++) {4: if (arr[i].compareTo(best) > 0) { | T=String, i=2, compareTo=-10, best="kiwi" | — |
| 9 | 8: return best;14: System.out.println(max(fruits)); | T=String, best="kiwi" | kiwi |
In the first step of Table 4.5.12 two arrays are built. Both are suitable: Integer and String implement Comparable with their own types. The numbers in the array are boxed automatically. In the second step the compiler has inferred T as Integer. The first element is taken as the largest candidate: best = 7.
In the third step 12.compareTo(7) is positive (1); 12 is larger and best = 12. In the fourth step 5.compareTo(12) is negative (−1); best does not change. In the fifth step the loop ends and 12 is returned. The return type is T, that is Integer; no cast is needed.
T = Integer: since 12 is larger than 7, it becomes the new candidate. On the right T = String: since “kiwi” comes after “elderberry” in dictionary order, it becomes the new candidate.In the sixth step the same method is called, this time with T = String. compareTo now compares strings in dictionary order: it returns the code difference of the first differing characters of the two strings. In the seventh step the first letters of “kiwi” and “elderberry” differ: 'k' − 'e' = 107 − 101 = 6. The result is positive and best = "kiwi" (Figure 4.5.17). In the eighth step “apricot” is compared with “kiwi”: 'a' − 'k' = 97 − 107 = −10; best does not change. In the last step “kiwi” is returned.
A single implementation has worked correctly with two different types. Thanks to the upper bound, the compareTo call is guaranteed at compile time: if max is called with an array of a type that has no compareTo, the program does not compile. It should not be forgotten that dictionary order rests on character codes. The codes of capital letters are smaller than those of lowercase letters; “Olive” comes before “apricot”.
4.5.8.4Wildcards and invariance
Integer is a subtype of Number; an Integer can be used anywhere in place of a Number. Is List<Integer> then a subtype of List<Number> too? The first answer that comes to mind is “yes”; Java's answer is “no”:
import java.util.*;
public class Immutability {
public static void main(String[] args) {
List<Integer> ints = Arrays.asList(1, 2, 3);
List<Number> x = ints;
}
}Immutability.java:5: error: incompatible types: List<Integer> cannot be converted to List<Number>
List<Number> x = ints;
^
1 errorInvariance: even if A is a subtype of B, List<A> is not a subtype of List<B>. Generic types do not automatically inherit the subtype relationship between their type arguments.
The reason for the rule is writing. If a List<Integer> could be assigned to a List<Number> variable, 2.5 could be added to the list through that variable, because 2.5 is a Number. But the list is really a list of integers and a Double would have got into it. Code that reads from the list and expects Integer would crash at run time. Java closes this door at compile time (Figure 4.5.18).
Integer is a subtype of Number; List<Integer> is not a subtype of List<Number>. The connection is made with a wildcard type: List<Integer> can be assigned to List<? extends Number>.Invariance is safe but reduces flexibility. If a method that sums the values in a list of numbers takes a List<Number> parameter, a List<Integer> cannot be given to it. Wildcards solve this problem:
?: any unknown type.? extends T:Tor a subtype of it. Such a list produces values; it is read asT.? super T:Tor a supertype of it. Such a list consumes values;Tis written into it.
static double add(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(add(ints) + " " + numbers);
// List<Number> x = ints; won't compile6.0 [1, 2, 2.5]
5.5add only reads from the list; its parameter is List<? extends Number>. So a List<Integer>, a List<Double> and a List<Number> can all be given. Every element read is at least a Number and doubleValue() can be called. 1 + 2 + 3 = 6.0 is found. fill only writes to the list; its parameter is List<? super Integer>. Whatever list arrives can take an Integer. 1 and 2 are added to the List<Number> given to it; the program itself adds 2.5 and the list becomes [1, 2, 2.5]. The last line added to the program that was run shows that the same add works with this mixed list too: 1 + 2 + 2.5 = 5.5.
Trying to write to a list marked with ? extends is a compile error. The compiler does not know the real type of the list; perhaps it is a List<Double> and 1 cannot be put into it:
import java.util.*;
public class ExtendsPrint {
static void add(List<? extends Number> list) {
list.add(1);
}
}ExtendsPrint.java:4: error: incompatible types: int cannot be converted to CAP#1
list.add(1);
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorThe CAP#1 in the message is a name the compiler invents for the unknown type. There is a short rule for remembering which wildcard to choose: PECS (Producer Extends, Consumer Super). A structure that produces values (is read) is written with extends, one that consumes values (is written) with super.
4.5.8.5Type erasure
Generic type information is mostly for the compiler. The compiler checks the type arguments, inserts the needed casts, and then erases this information. In the generated code Object (or the bound type in a bounded parameter) remains in place of T.
Type erasure is removing generic type arguments from the generated bytecode after they have been checked at compile time. At run time Box<String> and Box<Integer> are the same class.
Box<String> and a read without a cast. javac checks and erases the types; in the bytecode Box and the (String) cast that the compiler added remain.class Box<T> {
private T content;
// T make() { return new T(); } won't compile
}
// 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());true
BoxThe getClass() results of the two boxes are the same object: true. The name of the class is just Box; the type argument is not part of the name. Figure 4.5.19 shows the conversion the compiler makes: the compiler adds the (String) cast, which the programmer did not write, to the bytecode. Since the type check has passed, this cast never fails.
One consequence of type erasure is that T is unknown at run time. That is why new T() cannot be written; the JVM cannot know which class's object to create:
NewT.java:3: error: unexpected type
T fresh() { return new T(); }
^
required: class
found: type parameter T
where T is a type-variable:
T extends Object declared in class Box
1 errorFor the same reason a generic array cannot be created with new T[10]. The message is different this time:
NewTArray.java:2: error: generic array creation
T[] arr = new T[10];
^
1 error4.5.9Annotations
Adding to code information that only the compiler or a tool will read is sometimes useful: “this method overrides a method of the supertype”, “this class should no longer be used”, “this method is a test”. Java uses annotations for this kind of information.
An annotation is metadata added with @ to a class, method, field or parameter. An annotation does not change behavior by itself. The compiler, tools or the running program (through reflection) read it and act accordingly.
| Annotation | Who reads it? | What does it do? |
|---|---|---|
@Override | compiler | Reports an error if there is no such method in the supertype |
@Deprecated | compiler | Obsolete element; code that uses it gets a warning |
@SuppressWarnings("unchecked") | compiler | Silences the given warning |
@FunctionalInterface | compiler | Checks that the interface has only one abstract method |
@Test (JUnit) | test tool | Finds and runs the test methods |
Four of the annotations in the table are read by the compiler. @Override has proved useful several times in these notes: a method whose signature is misspelled is caught, thanks to the annotation, together with the real cause of the error. The check of @FunctionalInterface looks like this:
@FunctionalInterface
interface Operation {
int apply(int a, int b);
int negate(int a); // 2nd abstract method
}FuncTwo.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
Operation is not a functional interface
multiple non-overriding abstract methods found in interface Operation
1 errorWithout the annotation the interface would compile without trouble; the error would appear only when someone tries to assign a lambda to this interface, in another file. The annotation writes the intention into the code and has the compiler check it.
The programmer can define their own annotations too. An annotation is defined with @interface; its elements are written like methods and can take a default value with default. The @Task annotation below records the author and priority of a method. While running, the program examines its own class, finds the annotated methods and calls them:
@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);
}
}backup, Ayşe, 3
Backup doneThe two annotations above the annotation give information about the annotation itself. @Target(ElementType.METHOD) says that the annotation can be written only on methods. @Retention(RetentionPolicy.RUNTIME) says that the annotation is kept until run time. The loop goes over all the methods of the class Jobs. getAnnotation(Task.class) returns null if the method has no @Task. Only backup is annotated; its name, author and priority are printed, then m.invoke(jobs) calls the method and “Backup done” is printed. Since clean is not annotated, it is never called.
@Retention | Where does the annotation stay? |
|---|---|
SOURCE | Only in the source code (like @Override); discarded after the compiler has read it |
CLASS | In the .class file; reflection cannot see it (the default) |
RUNTIME | Read by reflection while running |
The difference in Table 4.5.14 is easy to try. If the same program is run with the @Retention value of the annotation set to CLASS, the annotation stays in the .class file but reflection cannot see it:
import java.lang.annotation.*;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
@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 class Main {
public static void main(String[] args) throws Exception {
int got = 0;
for (Method m : Jobs.class.getDeclaredMethods()) {
if (m.getAnnotation(Task.class) != null) got++;
}
System.out.println("annotation found: " + got);
}
}annotation found: 0Reflection is a program examining and using its own classes, methods, fields and annotations while running. It is done with classes such as Method and Field in the package java.lang.reflect.
Reflection is a powerful tool; testing tools and large application frameworks find annotated methods this way. It has a price too: calls such as m.invoke(...) do not pass through the compiler's checks, a wrong call is noticed only while running, and the code runs more slowly. That is why reflection is used not in ordinary application code but where it is really needed.
4.5.10Design patterns
Interfaces, abstract classes and lambdas are language tools. How to put these tools together for a given problem is a separate kind of knowledge. Experienced programmers have met the same design problems again and again and have given names to the solutions that work. All five patterns below are explained with small console programs; four of them rely directly on an interface.
4.5.10.1What is a pattern?
A design pattern is a tried and reusable solution template for a frequently met design problem. A pattern is not ready-made code to be copied; it is a shared vocabulary that names the problem, the solution and the trade-offs of the solution.
The common aim of patterns is to separate responsibilities and reduce dependencies between classes. A part with few dependencies can be changed without touching the others and can be tested on its own. Patterns are traditionally divided into three groups (Figure 4.5.20). Creational patterns deal with how objects are created, structural patterns with how objects are combined. Behavioral patterns arrange the cooperation of objects.
A pattern is useful only if it solves a real problem. A pattern added needlessly complicates the program. Patterns are concrete applications of more general design principles such as “few dependencies between components” and “composition over inheritance”. Composition means a class, instead of inheriting behavior, holding another object as a field and having it do the work.
4.5.10.2Singleton
Some classes should have a single object in the program. If the settings of the application, a log file or a hardware driver are kept in two copies, the copies may drift apart. The Singleton pattern ensures that the class has only one object and that this object is reached from a single place.
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
trueThe pattern has three parts. First, the constructor is private; new Settings() cannot be written outside the class:
SingletonNew.java:8: error: Settings() has private access in Settings
Settings a = new Settings();
^
1 errorSecond, the single object is kept in a private static final field inside the class. Third, this object is reached through a public static method (getInstance()). Since both calls return the same object, a == b gives true.
The order of the output is instructive too: the message “main started” is printed before “Settings created”. The JVM initializes the INSTANCE field once, when the class Settings is first used, that is at the first getInstance() call. Since the JVM does class initialization only once, this method is safe with several threads too.
The Singleton pattern has a serious drawback: it behaves like a hidden global variable. Every class that calls Settings.getInstance() from inside becomes invisibly tied to that single object. When testing these classes it becomes hard to put another object in place of the real settings. Often a better way is to pass the object as a parameter to the constructor of the class that needs it. Giving a dependency from outside is called dependency injection.
4.5.10.3Factory
Suppose a drawing program creates the shape the user chooses from a menu. The choice arrives as a string: “square”, “circle” … Deciding which class to create with an if chain everywhere scatters the creation code over the program. The Factory pattern gathers object creation in one place.
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.0A factory method is a method that produces an object and returns it as a superclass or interface type. The calling code does not know which concrete class was created.
The method ShapeFactory.create takes the kind and the size, creates the suitable object and returns it as the interface type Shape. The calling code knows not Square but only Shape. The class bodies abbreviated with … in the code are completed in the program that was run:
import java.util.Locale;
interface Shape { double area(); }
class Square implements Shape {
private final double a;
Square(double a) { this.a = a; }
public double area() { return a * a; }
}
class Circle implements Shape {
private final double r;
Circle(double r) { this.r = r; }
public double area() { return Math.PI * r * 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
}
}
}
public class Main {
public static void main(String[] args) {
Shape s = ShapeFactory.create("Square", 3);
System.out.println(s.area()); // 9.0
Shape u = ShapeFactory.create("triangle", 2);
System.out.println(u == null); // true
System.out.println(ShapeFactory.create("CIRCLE", 1).area());
System.out.println("CIRCLE".toLowerCase(Locale.forLanguageTag("tr-TR")) + " " + "CIRCLE".toLowerCase(Locale.ROOT));
}
}9.0
true
3.141592653589793
cırcle circleFor “square” and 3 the area is 9.0. Adding a new shape changes only the factory and the new class; the code that asks for shapes stays the same. For an unknown kind the factory returns null and the calling code checks the result: for “triangle” u == null gives true.
The detail toLowerCase(Locale.ROOT) is important for Turkish users. If toLowerCase() is called without a parameter, it works according to the computer's locale. In the Turkish locale the lowercase of the capital “I” is the dotless “ı”; “CIRCLE” becomes “cırcle” and does not match the "circle" branch. The last line of the program shows this difference: “cırcle” with Turkish rules, “circle” with the language-independent Locale.ROOT. Since the factory uses Locale.ROOT, the request “CIRCLE” produces the right shape and its area π · 1 · 1 = 3.141592653589793 is printed.
A factory is not needed everywhere. Writing a separate factory for objects that are already created simply is needless complexity; hiding an expression as clear as new Point(3, 4) behind a method only tires the reader.
4.5.10.4Observer
A weather station measures the temperature. When a new measurement arrives, a display should show it, an alert module should warn when the temperature exceeds 30 degrees, and a logger should store the measurement. If the station calls these three parts directly, every new part changes the code of the station. The Observer pattern reverses this dependency.
The observer pattern establishes a one-to-many relationship between a subject object and the observers registered with it. When the state of the subject changes, all registered observers are notified. The subject does not know the concrete class of the observers; it only calls the common interface.
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);
}
}update method of every registered observer when the temperature changes; it does not know what the observers do.Observer is an interface with a single method. Station keeps the observers in a list. add registers a new observer, and setTemp walks through the list and calls the update method of every observer. Since the interface has a single method, the observers can be written as lambdas too. In the program below two lambda observers are registered:
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);Display: 25 °C
Display: 34 °C
Alert: hot!| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 10: Station st = new Station(); | st=Station, list=[] | — |
| 2 | 11: st.add(d -> System.out.println("Screen: " + d + " °C"));4: void add(Observer g) { list.add(g); } | list=[display] | — |
| 3 | 12: st.add(d -> { if (d > 30) System.out.println("Alert: hot!"); });4: void add(Observer g) { list.add(g); } | list=[display, alert] | — |
| 4 | 13: st.setTemp(25);6: for (Observer g : list) g.update(d); | d=25 | — |
| 5 | 6: for (Observer g : list) g.update(d);11: st.add(d -> System.out.println("Screen: " + d + " °C")); | d=25, g=display | Screen: 25 °C |
| 6 | 6: for (Observer g : list) g.update(d);12: st.add(d -> { if (d > 30) System.out.println("Alert: hot!"); }); | d=25, g=alert | — |
| 7 | 14: st.setTemp(34);6: for (Observer g : list) g.update(d); | d=34 | — |
| 8 | 6: for (Observer g : list) g.update(d);11: st.add(d -> System.out.println("Screen: " + d + " °C")); | d=34, g=display | Screen: 34 °C |
| 9 | 6: for (Observer g : list) g.update(d);12: st.add(d -> { if (d > 30) System.out.println("Alert: hot!"); }); | d=34, g=alert | Alert: hot! |
In the first step of Table 4.5.15 the subject object is created; the observer list is empty. In the second step the first observer is added. It is a lambda and implements the single method of the Observer interface. The lambda is added to the list but does not run. In the third step the second observer is added; this observer speaks only above 30 degrees.
setTemp(34) has reached the second observer in the list; since the condition is true, the alert is printed.In the fourth step setTemp(25) is called and the loop walks through the list from the beginning. In the fifth step update(25) of the display observer is called and “Display: 25 °C” is printed. In the sixth step the alert observer is notified too, but since 25 > 30 is false, it prints nothing. In the seventh step a new measurement arrives: 34. In the eighth step the display prints the new value. In the ninth step the condition is true this time and “Alert: hot!” is printed (Figure 4.5.22).
The station has never known what any observer does. Adding a new observer does not change the code of the station. An observer does not have to be a lambda either; it can be an ordinary class that implements the interface. The logger below stores every measurement in a list:
import java.util.*;
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);
}
}
class Logger implements Observer {
private final List<Integer> measurements = new ArrayList<>();
public void update(int degrees) { measurements.add(degrees); }
List<Integer> getMeasurements() { return measurements; }
}
public class Main {
public static void main(String[] args) {
Station st = new Station();
Logger k = new Logger();
st.add(k);
st.setTemp(25);
st.setTemp(34);
st.setTemp(18);
System.out.println(k.getMeasurements());
}
}[25, 34, 18]The logger has been registered with the station once and has received all three measurements. This example also shows that an observer can be tested independently of the subject: the logger's list is the proof that the station really passes on every measurement. The Observer pattern is used wherever “tell me when something happens” is needed, from button clicks in graphical interfaces to cell updates in spreadsheets.
4.5.10.5Strategy
The checkout of a store computes the amount to pay. A 10% discount is applied to students, and in the campaign period 50 TL is deducted above 200 TL; tomorrow another rule may come. If the checkout knows these rules itself with an if chain, every new rule changes the code of the checkout.
The strategy pattern puts interchangeable algorithms behind a common interface. The object that uses the algorithm delegates the job to the strategy object given to it; when the strategy changes, its behavior changes without its code changing.
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.0225.0Checkout does not compute the discount itself. It keeps the Discount object given in the constructor in a field and delegates the job to it when due is called. StudentDiscount is an implementation of this interface: 250 · 0.90 = 225.0. Since the interface has a single method, the strategy can be a lambda too. The program below uses the same Checkout class with three different strategies:
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));225.0
200.0
120.0
7.0| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 8: Checkout student = new Checkout(t -> t * 0.90); | student=Checkout(10%) | — |
| 2 | 9: Checkout promo = new Checkout(t -> t >= 200 ? t - 50 : t); | promo=Checkout(200 and above −50) | — |
| 3 | 10: System.out.println(student.due(250));5: double due(double amount) { return strategy.apply(amount); } | amount=250.0 | 225.0 |
| 4 | 11: System.out.println(promo.due(250));5: double due(double amount) { return strategy.apply(amount); } | amount=250.0 | 200.0 |
| 5 | 12: System.out.println(promo.due(120));5: double due(double amount) { return strategy.apply(amount); } | amount=120.0 | 120.0 |
| 6 | 14: System.out.println(new Checkout(t -> 7).due(100)); | amount=100.0 | 7.0 |
In the first step of Table 4.5.16 the 10% discount lambda is attached to the first checkout. In the second step the same Checkout class is built with another strategy: if the amount is 200 TL or above, 50 TL is deducted. In the third step student.due(250) delegates the job to the strategy: 250 × 0.90 = 225.0. In the fourth step the campaign strategy runs: since 250 ≥ 200, 250 − 50 = 200.0. In the fifth step 120 < 200 and there is no discount: 120.0. The behavior has changed without any change in the code of the checkout.
t × 0.90, t ≥ 200 ? t − 50 : t and a constant strategy that returns 7 whatever the amount.The purpose of the sixth step is different. Instead of a real discount rule, a constant strategy that returns 7 whatever the amount is attached (Figure 4.5.23). The result is 7.0; the int value that the lambda t -> 7 returns is widened because the return type of the method is double. This line tests not the discount computation but only Checkout itself: does Checkout delegate the job to the strategy correctly? When the constant strategy is attached, the result can come only from the strategy; if 7.0 is seen, the delegation is correct. Testing one part alone by putting a simple fake object in place of the part it depends on has become possible because the strategy is given from outside.
The best-known example of a strategy in the Java library is sorting. The lambda in the call names.sort((a, b) -> a.length() - b.length()) is a Comparator strategy; the sorting algorithm stays the same, the comparison criterion changes.
4.5.10.6MVC
In programs that interact with the user, three different jobs tend to get mixed up: the data itself and its rules, showing the data on the screen, and reacting to the user's input. Putting these three jobs in one class means a small change made on the screen can break the data rules.
MVC (Model–View–Controller) is an architectural pattern that divides the program into three responsibilities. The model holds the data and the rules, the view only displays, the controller takes the input and manages the model and the view.
Let us take the responsibilities one by one. The model (Student, getName()) contains the data and the rules. It knows nothing of the screen; it can be tested without a screen. The view (StudentView) only displays; its show(name) method writes to the console. The controller (StudentController) takes the input and manages both sides; update() reads the model and gives the result to the view.
Student m = new Student("Ayşe");
StudentView g = new StudentView();
StudentController d =
new StudentController(m, g);
d.update(); // g.show(m.getName())The full form of the three classes used in this short excerpt is in the program below:
class Student {
private final String name;
Student(String name) { this.name = name; }
String getName() { return name; }
}
class StudentView {
void show(String name) { System.out.println("Student: " + name); }
}
class StudentController {
private final Student model;
private final StudentView view;
StudentController(Student model, StudentView view) {
this.model = model;
this.view = view;
}
void update() { view.show(model.getName()); }
}
public class Main {
public static void main(String[] args) {
Student m = new Student("Ayşe");
StudentView g = new StudentView();
StudentController d =
new StudentController(m, g);
d.update(); // g.show(m.getName())
}
}Student: AyşeThe controller receives the model and view objects in its constructor. This too is dependency injection: the controller does not create the model and view it will work with; it receives them from outside. Changing the view, for example writing the name to a file instead of the console, affects only StudentView; the model does not change at all. Application frameworks implement MVC in different ways. There is no single “right” class structure; what they share is the separation of the three responsibilities.
4.5.10.7When a pattern is not used
A side effect of learning patterns is the wish to use them where they are not needed. There are four common mistakes:
- Making Singleton a global variable. State that can be reached and changed from everywhere ties the parts of the program together invisibly.
- A needless factory. Writing a separate class for a creation as simple as
new Point(3, 4). - A needless observer. Building an event system when a single direct method call is enough; the flow of the program becomes harder to follow.
- Using a pattern for its name's sake. The problem comes first, then the pattern. Before adding a pattern, two questions are asked: “Which change does it make easier? Which dependency does it reduce?”
Strategy and dependency injection make it possible to put a simple fake object in place of a real part. Attaching a constant strategy to the checkout and giving a fake payment object to the payment method are examples. Looked at the other way round, a class that is hard to test on its own often shows that its design should be reviewed.
4.5.11Worked problems and exercises
4.5.11.1Worked problems
The problems below ask for the rules of abstract classes and interfaces to be applied together. The solution to each problem gives the rule with its reason; the outputs and compiler messages have been verified by running them.
For each of the fragments (a)–(e) below: does the fragment compile, and if not, what is the error? Of the fragments that compile, which one's object can be created with new?
// (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 { }(a) compiles. A has no abstract method at all but is marked abstract; this is valid. (b) does not compile. B has an abstract method, and is not abstract itself:
P57b.java:1: error: B is not abstract and does not override abstract method g() in B
class B { abstract void g(); }
^
1 error(c) does not compile. Since X is defined in an interface, it is implicitly public static final; I.X++ tries to assign it a new value:
P57c.java:3: error: cannot assign a value to static final variable X
void f() { I.X++; }
^
1 error(d) does not compile. h() in J is implicitly public; h() in C has package access and narrows access:
P57d.java:2: error: h() in C cannot implement h() in J
class C implements J { void h() { } }
^
attempting to assign weaker access privileges; was public
1 error(e) compiles. Since E is abstract too, it need not write k(); the obligation passes to the concrete subclasses of E. The answer to the second part of the question is “none”. In the two fragments that compile, A and E are abstract; new A() and new E() are compile errors too:
P57new.java:8: error: A is abstract; cannot be instantiated
A a = new A();
^
P57new.java:9: error: E is abstract; cannot be instantiated
E e = new E();
^
2 errorsWhat does the following program print? Why does Fish compile although it does not write sound()? What happens if public is removed from sound() in Cat? Does Noisy s = new Fish(); s.name(); compile?
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());A C A
cat: meow
fish: ...When the array is built, two objects are created. In new Cat() the superclass constructor runs first and prints “A ”, then the constructor of Cat prints “C ”. In new Fish() there is no constructor written in Fish; the default constructor the compiler adds calls super() and only “A ” is printed. So the first line becomes “A C A ”; the println() ends the line. In the loop name() runs the version of each object's own class. Cat has overridden sound(): “meow”. Fish has not; the default body of the interface runs: “...”.
The reason Fish compiles is that sound() is a default method, not an abstract one. Fish inherits it. To be concrete it is enough for it to write name(), the only abstract method. If public is removed from sound() in Cat, the method tries to override the public version in the interface with narrower access:
P58public.java:9: error: sound() in Cat cannot implement sound() in Noisy
String sound() { return "meow"; }
^
attempting to assign weaker access privileges; was public
1 errorThe last question tests the role of the reference type. The type of s is Noisy, and Noisy knows only sound(); even though the object has a name() method, the call does not compile:
P58swim.java:13: error: cannot find symbol
s.name();
^
symbol: method name()
location: variable s of type Noisy
1 errorThe constructor of an abstract class increases a static counter and the concrete method summary() calls the abstract area(). What does the program print?
abstract class Shape {
static int count = 0;
String name;
Shape(String name) { this.name = name; count++; }
abstract double area();
String summary() { return name + ":" + area(); }
}
class Square extends Shape {
double k;
Square(double k) { super("Square"); this.k = k; }
double area() { return k * k; }
}
class Circle extends Shape {
double r;
Circle(double r) { super("Circle"); this.r = r; }
double area() { return 3 * r * r; }
}
public class Main {
public static void main(String[] args) {
Shape[] d = { new Square(2), new Circle(1) };
for (Shape s : d) System.out.println(s.summary());
System.out.println(Shape.count);
}
}Square:4.0
Circle:3.0
2The element type of the array is the abstract Shape; the objects it points to are concrete. new Square(2) calls the constructor of Shape with super("Square"); no separate Shape object is created, the Shape part of the same object is built, and count becomes 1. new Circle(1) goes the same way and count becomes 2. In the loop summary() comes from Shape; the area() call inside it is bound to the class of this. For Square 2 · 2 = 4.0, for Circle 3 · 1 · 1 = 3.0 is found. The last line prints the static counter that counted the two constructor calls: 2.
Three unrelated classes implement the same Priced interface. At the end of the loop, what are the total and the price of the most expensive item?
interface Priced { double price(); }
class Book implements Priced {
public double price() { return 40; }
}
class Pen implements Priced {
int count;
Pen(int count) { this.count = count; }
public double price() { return 7.5 * count; }
}
class Ticket implements Priced {
public double price() { return 25; }
}
public class Main {
public static void main(String[] args) {
Priced[] cart = { new Book(), new Pen(4),
new Ticket() };
double total = 0;
Priced mostExpensive = cart[0];
for (Priced f : cart) {
total += f.price();
if (f.price() > mostExpensive.price()) mostExpensive = f;
}
System.out.println(total + " " + mostExpensive.price());
}
}95.0 40.0The element type of the array is an interface. The only thing Book, Pen and Ticket have in common is the Priced contract. mostExpensive starts with the first element, the book. In the first round f points to the book: price 40.0, total 40.0; since 40 > 40 is false, the most expensive does not change. In the second round f points to the pen: 7.5 × 4 = 30.0, total 70.0; 30 > 40 is false. In the third round the ticket: 25.0, total 95.0; 25 > 40 is false. The output is “95.0 40.0”. The same f.price() call has run a method of a different class in each round. To add a new Priced class, the loop does not change.
incTwice() is a default method written once in the interface. How many increments does it make on the two objects? What does the program print?
interface Counter {
int value();
void inc();
default boolean isZero() { return value() == 0; }
default void incTwice() { inc(); inc(); }
}
class Simple implements Counter {
private int d;
public int value() { return d; }
public void inc() { d++; }
}
class Doubling extends Simple {
@Override public void inc() {
super.inc(); super.inc();
}
}
public class Main {
public static void main(String[] args) {
Counter a = new Simple();
Counter b = new Doubling();
a.incTwice();
b.incTwice();
System.out.println(a.value() + " " + b.value()
+ " " + b.isZero());
}
}2 4 falsea is a Simple. In a.incTwice() the default body calls inc() twice; this call is this.inc() and is bound to the version of Simple: d becomes first 1, then 2. b is a Doubling. The same default body runs, but this is now a Doubling, and the overridden inc() calls super.inc() twice at each call: d becomes 2, then 4. The field d of Doubling comes from Simple; since it is private, it is changed only by the methods of Simple. Finally isZero() is a default method too; value() is 4 and the result is false. The output is “2 4 false”. A single default method has behaved differently on the two objects thanks to the methods the calling class overrides.
The necessary imports have been made. What does the program print?
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
IntBinaryOperator f = (a, b) -> a * b + 1;
IntUnaryOperator g = x -> x * x;
int t = f.applyAsInt(3, 4) + g.applyAsInt(5);
System.out.println(t);
List<Integer> l =
Arrays.asList(5, 8, 3, 12, 7);
System.out.println(l.stream()
.filter(s -> s > 5)
.map(s -> s / 2)
.collect(Collectors.toList()));
}
}38
[4, 6, 3]f.applyAsInt(3, 4) runs the lambda with a = 3, b = 4: 3 · 4 + 1 = 13. g.applyAsInt(5) gives 5 · 5 = 25. Both values are int and their sum is 38. In the stream filter(s -> s > 5) keeps the elements greater than 5, preserving their order: 8, 12, 7. map(s -> s / 2) transforms each of them. The division is integer division: 8 / 2 = 4, 12 / 2 = 6, 7 / 2 = 3. The result is [4, 6, 3].
4.5.11.2Exercises
The exercises below require writing code. After each there is a possible solution and its result.
Exercise 1. An abstract Employee class: a name field, a constructor, an abstract double salary() and an info() that prints the name and salary. Subclasses: FullTime, which earns 30000 a month, and Hourly, which earns 120 hours × 200 TL. info() is called in an Employee[] array. Two small questions are answered in the same program: in the interface Shape2D, which has an abstract double area() and a default summary() returning "Area: " + area(), what does summary() return for Triangle(6, 4)? For interface Account { static int add(int a, int b) … } and class Simple implements Account {}, what do Account.add(3, 4) and Simple.add(3, 4) give?
abstract class Employee {
private final String name;
Employee(String name) { this.name = name; }
abstract double salary();
void info() { System.out.println(name + ": " + salary()); }
}
class FullTime extends Employee {
FullTime(String name) { super(name); }
double salary() { return 30000; }
}
class Hourly extends Employee {
private final int hours;
private final double fee;
Hourly(String name, int hours, double fee) { super(name); this.hours = hours; this.fee = fee; }
double salary() { return hours * fee; }
}
interface Shape2D {
double area();
default String summary() { return "Area: " + area(); }
}
class Triangle implements Shape2D {
private final double base, height;
Triangle(double base, double height) { this.base = base; this.height = height; }
public double area() { return base * height / 2; }
}
interface Account { static int add(int a, int b) { return a + b; } }
class Simple implements Account { }
public class Main {
public static void main(String[] args) {
Employee[] employees = { new FullTime("Ayşe"), new Hourly("Ali", 120, 200) };
for (Employee c : employees) c.info();
System.out.println(new Triangle(6, 4).summary());
System.out.println(Account.add(3, 4));
}
}Ayşe: 30000.0
Ali: 24000.0
Area: 12.0
7info() is concrete and written once in Employee; the salary() inside it runs the formula of each object's own class: 30000.0 and 120 · 200 = 24000.0. The area of the triangle is 6 · 4 / 2 = 12.0 and the default summary() returns “Area: 12.0”. Account.add(3, 4) gives 7. Simple.add(3, 4) does not compile, because the static methods of an interface are not inherited:
SimpleAdd.java:5: error: cannot find symbol
System.out.println(Simple.add(3, 4));
^
symbol: method add(int,int)
location: class Simple
1 errorExercise 2. sealed abstract class Shape permits Square, Circle is written; Square is final, Circle is non-sealed. Do Ellipse extends Circle and Triangle extends Shape compile? In the same program a “fish that is both an animal and able to swim” is also designed.
sealed abstract class Shape permits Square, Circle { abstract double area(); }
final class Square extends Shape {
double a = 2;
double area() { return a * a; }
}
non-sealed class Circle extends Shape {
double r = 1;
double area() { return 3 * r * r; }
}
class Ellipse extends Circle { }
abstract class Animal { }
interface Swimmable { void swim(); }
class Fish extends Animal implements Swimmable {
public void swim() { System.out.println("Fish is swimming"); }
}
public class Main {
static String name(Shape s) {
return switch (s) {
case Square k -> "square";
case Circle c -> "circle";
};
}
public static void main(String[] args) {
Shape[] arr = { new Square(), new Circle(), new Ellipse() };
for (Shape s : arr) System.out.println(name(s) + " " + s.area());
Swimmable y = new Fish();
y.swim();
Animal h = (Animal) y;
System.out.println(h instanceof Swimmable);
}
}square 4.0
circle 3.0
circle 3.0
Fish is swimming
trueEllipse compiles: since Circle is non-sealed, anyone can extend it. A switch recognizes an Ellipse as a Circle and says “circle”; its area comes from Circle too. Triangle is not in the permits list:
SealedClass.java:4: error: class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)
class Triangle extends Shape { }
^
1 errorSince Square is final, it is not possible to extend it either; this time the message speaks not of sealing but of final:
SealedFinalSub.java:4: error: cannot inherit from final Square
class BigSquare extends Square { }
^
1 errorIn the fish design there is both kinship and ability. Animal is an abstract class, and the ability to swim is the interface Swimmable: class Fish extends Animal implements Swimmable. The same object can be held as Swimmable and cast to Animal; both are different types of the same object.
Exercise 3. In class Square implements GeometricShape, public void Draw() { … } is written. What happens? What changes if @Override is added above the method?
Draw and draw are different names; Java distinguishes upper and lower case. Draw() is a new method and draw() is still missing: Square is not abstract and does not override abstract method draw() in GeometricShape. When @Override is added, the compiler gives a second message and points to the real place of the error:
NoOverride.java:4: error: Square is not abstract and does not override abstract method draw() in GeometricShape
class Square implements GeometricShape {
^
NoOverride.java:5: error: method does not override or implement a method from a supertype
@Override
^
2 errors4.5.12Common mistakes
The compiler catches almost all mistakes with abstract classes and interfaces. The messages are in English and formulaic; once recognized, the place of the error is found at once. The boxes below give the most frequent ones with their messages.
Creating an object from an abstract class. new Shape("?") → Shape is abstract; cannot be instantiated. The object is created from a concrete subclass; the type of the variable can stay abstract: Shape s = new Square(3);. The same message comes when an object is created from an interface.
Forgetting to write an abstract method. Circle is not abstract and does not override abstract method draw() in Shape. Either the method is written or the class is made abstract. When implementing an interface the message is the same; only the last word is the name of the interface.
Writing a body for an abstract method, or not making the class abstract. abstract void draw() { } → abstract methods cannot have a body. A method is either abstract or has a body. class Shape { abstract void draw(); } → Shape is not abstract and does not override abstract method draw() in Shape.
Contradictory modifiers. abstract final, private abstract, static abstract → illegal combination of modifiers. All three modifiers prevent overriding; an abstract method and an abstract class exist for subclasses.
Deriving from two classes. class C extends A, B → '{' expected. A class can have a single extends and many implements. That the message does not explain the error makes it harder to recognize.
Calling a method that is not in the type of the reference. Flyable u = new Duck(); u.swim(); → cannot find symbol. Which methods can be called is decided not by the object but by the type of the reference. The method is called through a reference of a type that knows it (Swimmable or Duck).
Not resolving conflicting default methods. class Clerk inherits unrelated defaults for greet() from types Greeter and Welcomer. The method is overridden in the class; the version of the wanted interface can be called with InterfaceName.super.greet().
Forgetting the sealing rules. A subtype that is not permitted: class is not allowed to extend sealed class: Animal. A permitted subtype with no modifier: sealed, non-sealed or final modifiers expected.
Changing a local variable that a lambda uses. local variables referenced from a lambda expression must be final or effectively final. A lambda carries a copy of the value of the local variable; the variable cannot be changed afterwards. A value that has to change is kept in a field.
Thinking generic types inherit the subtype relationship. List<Number> x = ints; (ints is a List<Integer>) → incompatible types: List<Integer> cannot be converted to List<Number>. A method that reads declares its parameter as List<? extends Number>, a method that writes as List<? super Integer>.
4.5.13Summary
- Abstraction is hiding the detail and defining “what is done”, leaving “how” to the subtypes. Java has two tools for it: the abstract class and the interface.
- An abstract class is defined with
abstract class; no object can be created from it. It can contain fields, constructors, abstract and concrete methods. Its constructor builds the part of a subclass object that comes from it and is called withsuper(...). - An abstract method has no body and ends with
;. A concrete subclass must implement it. It cannot be written together withprivate,staticandfinal. - The template method defines the skeleton of an algorithm in the superclass (in a
finalmethod); the varying steps are abstract methods written in the subclasses. - An interface is a contract. Its methods are implicitly
public abstract, its fieldspublic static final; it has no instance fields and no constructor. A class can write a singleextendsand manyimplements; the implementing method must bepublic. - The type of the reference decides which methods can be called, and the class of the object decides which body runs. Programming to an interface type gives loose coupling.
- A lambda expression is an anonymous function written in the form
(parameters) -> expressionand is assigned to a functional interface (an interface with a single abstract method) (Java 8+). It runs not when it is defined but when the interface's method is called. The local variables it uses must be effectively final. - Methods with bodies in interfaces: default (Java 8, inherited),
static(Java 8, called only with the interface name) andprivate(Java 9, only inside the interface). Conflicting default methods are overridden by the class; a method in the superclass beats a default method. - A sealed type (
sealed, Java 17+) limits its subtypes withpermits; each subtype isfinal,sealedornon-sealed. In a closed hierarchy aswitchcan cover every case without adefaultbranch. - An abstract class groups closely related classes with common state and code (“is a”); an interface gives abilities to unrelated classes (“can do”). Often the two are used together.
- Generics write classes and methods with type parameters (
Box<T>,<T extends Parent>). Type errors are caught at compile time. Generic types are invariant; flexibility comes from wildcards (? extends,? super). Type information is erased after compilation. - Annotations are metadata like
@Override;RUNTIMEannotations are read by reflection. - Design patterns are tried solution templates: Singleton (one object), Factory (gathering creation), Observer (notifying registered objects of changes), Strategy (an interchangeable algorithm) and MVC (separating data, display and control). A pattern is used only if it solves a real problem.
4.5.14Key terms
- abstraction
- abstract class
- abstract method
- concrete class
- template method
- constructor chaining
- interface
- implement
- multiple inheritance
- dynamic binding
- declared type / actual type
- loose coupling
- lambda expression
- functional interface
- anonymous class
- effectively final
- default method
- sealed class / interface
- generics
- bounded type parameter
- wildcard
- type erasure
- annotation
- reflection
- design pattern
- factory method
- dependency injection
- MVC (Model–View–Controller)
4.5.15Test Yourself
The constructor of the abstract class
Documentprints"D ", and the constructors of the subclassesLetterandBookprint"L "and"B "respectively. The methodfinal String label() { return name + "(" + pages() + ")"; }ofDocumentcalls the abstractpages();Letterreturns 1,Book(int chapters)returnschapters * 20. What does the lineDocument[] b = { new Letter(), new Book(3) };print? Then what is thelabel()of each element?Answer
In each object the constructor of the abstract superclass runs first, then that of the subclass:
D L D B. No separateDocumentobject is created.label()is written once inDocumentbutpages()is bound to the class of each object:letter(1), and with 3 · 20 = 60,book(60).The interface
Counterhas an abstractint count()anddefault int twice() { return 2 * count(); }; the interfaceMeterhasdefault int twice() { return 100; }. The classBoth implements Counter, Meterreturns 7 incount()and writestwice()asCounter.super.twice() + Meter.super.twice(). What isnew Both().twice()? What would happen ifBothdid not writetwice()?Answer
The default body of
Countercallsthis.count()and finds 2 · 7 = 14; that ofMeterreturns 100. The result is 114. If the method were not written, the class would not compile, because the two interfaces bring two default bodies with the same signature:inherits unrelated defaults for twice().After the definitions
Function<Integer, Integer> f = x -> x + 1;andFunction<Integer, Integer> g = x -> x * 3;, what aref.apply(g.apply(4))andg.apply(f.apply(4))? When the definition lines run, does either of the lambdas run?Answer
The inner call runs first.
g.apply(4) = 12,f.apply(12) = 13.f.apply(4) = 5,g.apply(5) = 15. The result is13 15. The definition lines only create two interface objects; the bodies run only whenapplyis called.l.removeIf(s -> s.length() == 4);is applied to the listList<String> l = new ArrayList<>(List.of("plum", "pear", "kiwi", "fig", "apricot"));. What becomes of the list? Which functional interface is the parameter ofremoveIf?Answer
The four-letter “plum”, “pear” and “kiwi” are removed; the remaining list is
[fig, apricot]and the order of the rest is preserved.removeIftakes aPredicate: thetestmethod that returnsbooleanfor each element.removeIfwas added to theCollectioninterface as a default method in Java 8.The generic method
maxof this chapter is called withInteger[] d = {3, 9, 4}andString[] a = {"Olive", "apricot", "Apple"}. What are the results? Why is the second result surprising at first sight?Answer
For the numbers 9 is found. For the strings
compareTocompares character codes, and the codes of capital letters (O = 79, A = 65) are smaller than those of lowercase letters (a = 97). So the string that comes last in dictionary order, the “largest”, isapricot. The result is9 apricot.The sealed interface
Animalpermits onlyCatandDog, and theswitchin the methodkindhas two branches and nodefaultbranch. One dayBirdis added to thepermitslist andfinal class Bird implements Animalis written. What happens? What would have happened if theswitchhad adefaultbranch from the start?Answer
The method
kindstops compiling:the switch expression does not cover all possible input values. The compiler points to every place where the new type is not handled. With adefaultbranch the program would compile andBirdwould silently fall intodefault; the missing branch would be noticed only at run time, perhaps never.In class
Machine,public void work()prints “Machine is working”. In the interfacePrinter,default void work()prints “Printing”. Forclass Photocopy extends Machine implements Printer { }, what doesPrinter y = new Photocopy(); y.work();print? Why does the class compile?Answer
“Machine is working” is printed. If a class receives a method with the same signature both from its superclass and from the default body of an interface, the method in the class hierarchy wins. In this case there is no conflict, so the class compiles. That the reference has type
Printerdoes not change the result.Predicate<Integer> p = x -> { counter.add(x); return x > 2; };is defined (counteris an emptyArrayList<Integer>). A loop overList.of(1, 5, 2, 8)increasesnifp.test(x)is true. After the loop what arenandcounter? What would happen ifcounterwere anintlocal variable and the lambda increased it withcounter++?Answer
The lambda runs once per
testcall and adds the number it sees to the list. 5 and 8 satisfy the condition:n = 2,counter = [1, 5, 2, 8]. Adding an element to the list is not assigning a new value to the variablecounter; the variable always points to the same list and stays effectively final. Increasing anintlocal variable withcounter++, however, is assigning it a new value and does not compile:local variables referenced from a lambda expression must be final or effectively final.
4.5.16Further reading
- Oracle, The Java Tutorials, the lessons “Interfaces and Inheritance”, “Lambda Expressions” and “Generics”: cover abstract classes, interfaces, default methods, lambdas and generics with short, runnable examples; online and free.
- J. Bloch, Effective Java (3rd ed., Addison-Wesley, 2018): Item 20 (“Prefer interfaces to abstract classes”) discusses the choice between an interface and an abstract class, Item 31 the PECS rule for wildcards, and Item 42 the reasons for preferring lambdas to anonymous classes.
- E. Freeman and E. Robson, Head First Design Patterns (2nd ed., O'Reilly, 2020): explains the Strategy, Observer, Factory and Singleton patterns for beginners, with Java examples and plenty of drawings.
- E. Gamma, R. Helm, R. Johnson and J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1994): the foundational book that established the vocabulary of design patterns; it defines the intent, structure and trade-offs of each pattern.
4.5.17References
- Oracle, The Java Tutorials: “Abstract Methods and Classes”, “Interfaces”, “Default Methods”, “Lambda Expressions”, “Generics”, “Annotations”.
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition (8.1.1.1 abstract Classes, 8.1.1.2 sealed, non-sealed, and final 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.
- J. Bloch, Effective Java, 3rd ed., Addison-Wesley, 2018 (Items 20, 31 and 42).
- E. Freeman and E. Robson, Head First Design Patterns, 2nd ed., O'Reilly, 2020.