The Range class

Report a typo

The Range class is supposed to represent an integer range. Its invariants restrict the start and the end of the range so that the value of the from field is not greater than the one of the to field.

Unfortunately, there's a chance that the invariants can break during serialization/deserialization. You need to improve the class so that it preserves the invariants during deserialization (i.e. from <= to). When the deserialized object breaks the invariant, throw IllegalArgumentException. Pay attention to the constructor since it provides a good example of the required behavior.

Write a program in Java 17
/**
Represents inclusive integer range.
*/
class Range implements Serializable {

private static final long serialVersionUID = 1L;

/** @serial */
private final int from;
/** @serial */
private final int to;

/**
* Creates Range.
*
* @param from start
* @param to end
* @throws IllegalArgumentException if start is greater than end.
*/
public Range(int from, int to) {
if (from > to) {
throw new IllegalArgumentException("Start is greater than end");
}
this.from = from;
this.to = to;
}

public int getFrom() {
return from;
}

public int getTo() {
return to;
}

}
___

Create a free account to access the full topic