Java Callbacks, Comparator and Object Cloning
Three classic uses of Java interfaces: callbacks with listener interfaces and timers, custom sort orders with Comparator and its contract, and object cloning with Cloneable, shallow vs deep copies, covariant clone, array clone, and modern alternatives like copy constructors.
kvi5hnuCode Sprout team member13 min readOn this page
The previous articles showed how to declare and implement interfaces. Now let's look at three classic jobs interfaces do in the standard library: callbacks, custom comparisons with Comparator, and cloning with the Cloneable marker interface. The first two lead straight into lambda expressions, in the next article.
Interfaces and Callbacks
A common pattern in programming is the callback: you specify the action that should happen whenever a particular event occurs. For example, you may want an action to run when a button is clicked, a message arrives or a time interval elapses.
The javax.swing package has a Timer class that notifies you whenever a time interval has elapsed. If part of your program displays a clock, you can ask to be notified every second to update the clock face. When you construct the timer, you set the interval and tell it what to do each time.
How do you tell the timer what to do? In many languages, you supply the name of a function the timer should call. The Java standard library takes an object-oriented approach: you pass an object of some class, and the timer calls one of its methods. Passing an object is more flexible than passing a function, because the object can carry additional information.
The timer needs to know which method to call, so it requires an object of a class that implements the ActionListener interface from java.awt.event:
public interface ActionListener {
void actionPerformed(ActionEvent event);
}
The timer calls actionPerformed when the interval has expired. To print a message and beep every second, define a class that implements ActionListener and put the statements in actionPerformed:
class TimePrinter implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("At the tone, the time is "
+ Instant.ofEpochMilli(event.getWhen()));
Toolkit.getDefaultToolkit().beep();
}
}
The ActionEvent parameter describes the event. event.getWhen() returns the event time in milliseconds since the "epoch" (January 1, 1970, UTC), and Instant.ofEpochMilli turns it into a readable value such as 2026-11-13T09:00:01.550Z.
Next, construct a listener object and pass it to the Timer constructor, then start the timer:
var listener = new TimePrinter();
var timer = new Timer(1000, listener); // interval in milliseconds, then the listener
timer.start();
Here's a complete program. It needs a desktop environment, because it shows a dialog that keeps the program alive. Without the dialog, the program would end as soon as main exits:
import java.awt.*;
import java.awt.event.*;
import java.time.*;
import javax.swing.*;
public class TimerTest {
public static void main(String[] args) {
var listener = new TimePrinter();
// construct a timer that calls the listener once every second
var timer = new Timer(1000, listener);
timer.start();
// keep program running until the user selects "OK"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
| API | Purpose |
|---|---|
javax.swing.Timer(int interval, ActionListener l) | Notifies l every interval milliseconds |
void start(), void stop() | Start or stop the notifications |
JOptionPane.showMessageDialog(Component parent, Object message) | Dialog with an OK button, centered on parent or on the screen if parent is null |
Toolkit.getDefaultToolkit().beep() | Emits a beep |
The demo below uses the same pattern without a GUI: a SimulatedClock calls back a TickListener on every simulated tick, so the output is deterministic. Event listeners in GUIs, Runnable tasks for threads, Comparator for sorting and handlers in web frameworks are all callbacks.
The Comparator Interface
You've seen how to sort objects whose class implements Comparable. You can sort an array of strings because String implements Comparable<String>, and String.compareTo compares in dictionary order.
Now suppose we want to sort strings by increasing length. We can't make String implement compareTo in two ways, and String isn't ours to modify anyway. For this situation, Arrays.sort has a second version that takes an array and a comparator, an instance of a class implementing the Comparator interface:
public interface Comparator<T> {
int compare(T first, T second);
}
To compare strings by length, implement Comparator<String>:
class LengthComparator implements Comparator<String> {
public int compare(String first, String second) {
return first.length() - second.length();
}
}
(Subtraction is fine here: string lengths are non-negative, so it can't overflow.) To compare, make an instance:
var comp = new LengthComparator();
if (comp.compare(words[i], words[j]) > 0) . . .
Contrast this with words[i].compareTo(words[j]). The compare method is called on the comparator object, not on the string. Even though LengthComparator has no state, you still need an instance, because compare isn't a static method.
To sort an array, pass a comparator to Arrays.sort:
String[] friends = { "Peter", "Paul", "Mary" };
Arrays.sort(friends, new LengthComparator());
Now the array is ["Paul", "Mary", "Peter"]. In general, elements that compare as equal could end up in either order, but Arrays.sort for objects is stable: equal elements keep their original relative order, so Paul stays before Mary. In the lambdas article you'll see how to write a Comparator far more concisely, and later how Comparator.comparing builds them for you.
The String class provides a ready-made comparator for case-insensitive comparison: Arrays.sort(friends, String.CASE_INSENSITIVE_ORDER). The plain compareTo puts all uppercase letters before lowercase ones, which is rarely what users expect. For language-aware ordering of names, use a java.text.Collator.
The comparator contract
A comparator must obey three rules:
- Reflexivity: when
xandyare equal, the result is 0. - Antisymmetry: swapping the arguments swaps the sign of the result.
- Transitivity: if
xcomes beforeyandybeforez, thenxcomes beforez.
The sorting algorithm Arrays.sort uses for objects (TimSort, a merge sort hybrid) doesn't check these rules for every element. But sometimes it detects a violation at trivial cost and throws IllegalArgumentException: Comparison method violates its general contract!.
Everything So Far in Code
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.*;
public class Solution {
public static void main(String[] args) throws CloneNotSupportedException {
// --- callbacks: a simulated clock notifies a listener on every tick ---
var clock = new SimulatedClock(Instant.parse("2026-11-13T09:00:00Z"));
clock.addListener(new TimePrinter());
clock.run(3, 1000);
// --- Comparator: sorting strings by length ---
String[] friends = { "Peter", "Paul", "Mary" };
Arrays.sort(friends, new LengthComparator());
System.out.println(Arrays.toString(friends));
var comp = new LengthComparator();
System.out.println(comp.compare("Peter", "Paul") > 0);
String[] names = { "bob", "Alice", "carol", "Dave" };
Arrays.sort(names);
System.out.println(Arrays.toString(names)); // uppercase first
Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(names));
// shuffle with Collections.shuffle, not with a random comparator
List<String> list = new ArrayList<>(List.of("a", "b", "c", "d", "e"));
Collections.shuffle(list, new Random(42));
System.out.println(list);
// --- cloning ---
var original = new Employee("Mira Okafor", 50000);
original.setStartDate(2000, 1, 1);
Employee alias = original; // copying the reference: same object
System.out.println(alias == original);
Employee copy = original.clone(); // a new object
copy.giveRaise(10);
copy.setStartDate(2002, 12, 31);
System.out.println("original=" + original);
System.out.println("copy=" + copy);
int[] luckyNumbers = { 2, 3, 5, 7, 11, 13 };
int[] cloned = luckyNumbers.clone(); // arrays have a public clone
cloned[5] = 12; // doesn't change luckyNumbers[5]
System.out.println(luckyNumbers[5] + " " + cloned[5]);
System.out.println(new Copyable("x") instanceof Cloneable);
try {
new NotCloneable().tryClone();
} catch (CloneNotSupportedException e) {
System.out.println("CloneNotSupportedException: " + e.getMessage());
}
}
}
/** The callback interface: whoever wants notifications implements it. */
interface TickListener {
void tick(Instant when);
}
class TimePrinter implements TickListener {
@Override
public void tick(Instant when) {
System.out.println("At the tone, the time is " + when);
}
}
/** Plays the role of a timer, but deterministically. */
class SimulatedClock {
private final List<TickListener> listeners = new ArrayList<>();
private Instant now;
SimulatedClock(Instant start) { now = start; }
void addListener(TickListener l) { listeners.add(l); }
void run(int ticks, long intervalMillis) {
for (int i = 0; i < ticks; i++) {
now = now.plusMillis(intervalMillis);
for (TickListener l : listeners) l.tick(now); // call back
}
}
}
class LengthComparator implements Comparator<String> {
@Override
public int compare(String first, String second) {
return first.length() - second.length(); // lengths are small, no overflow
}
}
class Employee implements Cloneable {
private final String name;
private double salary;
private Date startDate; // mutable on purpose, to show deep copying
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
startDate = new Date(0);
}
@Override
public Employee clone() throws CloneNotSupportedException {
// call Object.clone()
Employee cloned = (Employee) super.clone();
// clone mutable fields
cloned.startDate = (Date) startDate.clone();
return cloned;
}
/** Sets the start date; mutates the Date object in place. */
public void setStartDate(int year, int month, int day) {
long epochMillis = LocalDate.of(year, month, day)
.atStartOfDay(ZoneOffset.UTC).toEpochSecond() * 1000;
startDate.setTime(epochMillis);
}
public void giveRaise(double pct) {
salary += salary * pct / 100;
}
@Override
public String toString() {
return "Employee[name=" + name + ",salary=" + salary + ",startDate="
+ startDate.toInstant().atZone(ZoneOffset.UTC).toLocalDate() + "]";
}
}
record Copyable(String s) implements Cloneable { }
class NotCloneable {
Object tryClone() throws CloneNotSupportedException {
return clone(); // allowed to call (own class), but Object.clone checks for Cloneable
}
}
At the tone, the time is 2026-11-13T09:00:01Z
At the tone, the time is 2026-11-13T09:00:02Z
At the tone, the time is 2026-11-13T09:00:03Z
[Paul, Mary, Peter]
true
[Alice, Dave, bob, carol]
[Alice, bob, carol, Dave]
[b, c, d, e, a]
true
original=Employee[name=Mira Okafor,salary=50000.0,startDate=2000-01-01]
copy=Employee[name=Mira Okafor,salary=55000.0,startDate=2002-12-31]
13 12
true
CloneNotSupportedException: NotCloneable
Object Cloning
The rest of this article covers the Cloneable interface, which indicates that a class provides a safe clone method. Cloning isn't all that common and the details are technical, so you can skim this until you need it.
Copying versus cloning
Recall what happens when you copy a variable holding an object reference. The original and the copy are references to the same object, so a change through either variable affects the other:
var original = new Employee("Mira Okafor", 50000);
Employee copy = original;
copy.giveRaise(10); // oops: also changed original
If you want copy to be a new object that starts out identical to original but whose state can diverge, use clone:
Employee copy = original.clone();
copy.giveRaise(10); // OK: original unchanged
Shallow copies
It isn't quite that simple. clone is a protected method of Object, so your code can't simply call it on any object. And think about how Object can implement clone: it knows nothing about the object, so it can only make a field-by-field copy.
If all fields are numbers or other primitive values, copying them is fine. But if the object refers to subobjects, copying the field gives you another reference to the same subobject, so the original and the clone still share information. The default cloning operation is shallow: it doesn't clone the objects referenced inside other objects.

Does it matter? It depends:
- If the shared subobject is immutable, such as a
Stringor aLocalDate, sharing is safe. - It's also safe if the subobject simply never changes during the object's lifetime, with no mutators touching it and no methods leaking a reference to it.
- But quite often, subobjects are mutable, and you must redefine
cloneto make a deep copy that clones the subobjects as well.
In the example, startDate is a java.util.Date, which is mutable (setTime changes it), so it must be cloned too. That's why this example uses the old Date class: had startDate been an immutable LocalDate, no extra work would be needed.
Implementing clone
For every class, you decide whether
- the default
cloneis good enough, - the default
clonecan be patched up by callingcloneon the mutable subobjects, or cloneshouldn't be attempted at all.
The third option is the default. To choose the first or second, a class must
- implement the
Cloneableinterface, and - redefine
clonewith thepublicaccess modifier.
Here, the Cloneable interface has nothing to do with the normal use of interfaces. It doesn't declare clone, which is inherited from Object. It merely serves as a tag, indicating that the class designer understands the cloning process. Object.clone is so cautious that it throws a checked CloneNotSupportedException if the object's class doesn't implement Cloneable, as the last line of the demo shows.
Even if the default shallow copy is adequate, you still need to implement Cloneable, redefine clone as public, and call super.clone():
class Employee implements Cloneable {
// public access, change return type
public Employee clone() throws CloneNotSupportedException {
return (Employee) super.clone();
}
. . .
}
In Object, clone returns Object. In a subclass, you can declare the correct return type, an example of covariant return types (see polymorphism). Callers then don't need a cast.
That clone adds no functionality to Object.clone; it only makes the method public. For a deep copy, clone the mutable fields as well:
class Employee implements Cloneable {
. . .
public Employee clone() throws CloneNotSupportedException {
// call Object.clone()
Employee cloned = (Employee) super.clone();
// clone mutable fields
cloned.startDate = (Date) startDate.clone();
return cloned;
}
}
Object.clone threatens to throw CloneNotSupportedException whenever it's called on an object whose class doesn't implement Cloneable. Employee and Date do implement it, so the exception won't occur, but the compiler doesn't know that. Hence the throws clause.
Would it be better to catch the exception?
public Employee clone() {
try {
Employee cloned = (Employee) super.clone();
. . .
return cloned;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e); // can't happen: we are Cloneable
}
}
That's appropriate for final classes. Otherwise, leave the throws clause in place, which gives subclasses the option to throw CloneNotSupportedException if they can't support cloning.
Cloning and subclasses
Be careful with subclasses. Once Employee has a public clone, anyone can use it to clone Manager objects. Does Employee.clone do the job? It depends on Manager's fields. If it only adds a primitive bonus, there's no problem. But a subclass might add fields that need a deep copy, or that can't be cloned at all, and there's no guarantee its author fixed clone. That's exactly why Object.clone is protected. You lose that safety once you make clone public.
Arrays are the easy case: every array type has a public clone method that returns a new array of the same type, with copies of all elements:
int[] luckyNumbers = { 2, 3, 5, 7, 11, 13 };
int[] cloned = luckyNumbers.clone();
cloned[5] = 12; // doesn't change luckyNumbers[5]
For an array of objects, the copy is shallow: the new array refers to the same element objects.
Should you implement clone?
If your clients need deep copies, you probably should support copying. But clone is awkward: it relies on a marker interface, bypasses constructors, conflicts with final fields (you can't reassign a final field in clone), and needs a checked exception. Many experienced developers, including Joshua Bloch in Effective Java, recommend alternatives:
- a copy constructor:
public Employee(Employee other) { ... } - a static copy factory:
public static Employee copyOf(Employee other) - making the class immutable (records,
LocalDate), so copies are never needed
The design questions about deep versus shallow copies remain the same with any approach. Cloning is less common than you might think: only a small fraction of standard library classes implement clone.
Common questions
What's the modern way to write a comparator?
Use the static and default methods of Comparator: Comparator.comparing(Person::lastName).thenComparing(Person::firstName), comparingInt, reversed(), and nullsFirst/nullsLast. They're shorter and less error-prone than hand-written compare methods. The lambdas article covers them.
Is clone deprecated?
No, but it's widely considered a flawed design. For your own classes, prefer copy constructors, static copy factories or immutable types. clone is still the simplest way to copy an array (int[] copy = a.clone();).
Does Arrays.sort with a comparator work on primitive arrays?
No. Arrays.sort(int[]) sorts only in natural order. To sort primitives in a custom order, box them (Integer[]), sort an index array with a comparator, or sort and then reverse.
Why does my sort throw "Comparison method violates its general contract!"? Your comparator is inconsistent. Typical causes are subtraction overflow, comparing mutable fields that change during the sort, random results, or mixing comparisons that aren't transitive. TimSort detects some of these violations and throws instead of returning a wrongly sorted array.
Is Serializable a marker interface I should use?
It is a marker interface, but Java serialization has a long history of security problems. Avoid it for new designs. Use a well-defined format such as JSON or protocol buffers. If you must deserialise untrusted data, configure serialization filters (ObjectInputFilter).
Summary
- A callback passes an object implementing a listener interface (such as
ActionListener) to code that calls it back later, for example ajavax.swing.Timer. - A
Comparator<T>supplies an ordering separate from the class itself:Arrays.sort(a, comparator).String.CASE_INSENSITIVE_ORDERis built in. Comparators must be reflexive, antisymmetric and transitive; don't shuffle with random comparators. - Cloning creates a new object with the same state.
Object.clonemakes a shallow field-by-field copy and is protected. - To support cloning, implement the marker interface
Cloneable, overridecloneaspublic(with a covariant return type), callsuper.clone(), and clone mutable subobjects for a deep copy. - Arrays have a public
clone. For your own classes, copy constructors, copy factories or immutability are often simpler thanclone.
Practice Questions
Why does the Java library pass an object rather than a function to a Timer?
Java (before lambdas) had no way to pass a function, and an object is more flexible anyway: it can carry additional data and state that the callback method uses, such as a counter or a reference to a display.
Write a Comparator<String> that sorts by length and then alphabetically for equal lengths, without lambdas.
class LengthThenAlpha implements Comparator<String> {
public int compare(String a, String b) {
int diff = Integer.compare(a.length(), b.length());
return diff != 0 ? diff : a.compareTo(b);
}
}
What's wrong with Arrays.sort(cards, (a, b) -> random.nextInt(3) - 1) as a shuffle?
The comparator violates reflexivity, antisymmetry and transitivity. The result isn't a fair shuffle, and TimSort may throw "Comparison method violates its general contract!". Use Collections.shuffle.
Employee has fields String name, double salary, LocalDate startDate, and ArrayList<String> skills. Which fields must a deep clone copy explicitly?
Only skills, because ArrayList is mutable. String and LocalDate are immutable and double is primitive, so sharing or copying them by value is safe.
A class doesn't implement Cloneable but its own method calls super.clone(). What happens?
It compiles, since the class may call the protected method on itself, but at runtime Object.clone throws CloneNotSupportedException.
Name two alternatives to clone for copying objects.
A copy constructor, such as new Employee(other), or a static copy factory such as Employee.copyOf(other). Making the class immutable removes the need for copies altogether.
Previous: Java Interface Default, Static and Private Methods
Related reading
- Java Interface Default, Static and Private Methods
- Java Interfaces: Declaring and Implementing Interfaces
- Java Inheritance Design Hints: Best Practices for Class Hierarchies
- Java Reflection: Invoking Methods and Writing Generic Array Code
- Java Reflection: Analyzing Classes and Inspecting Objects at Runtime

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.