= Solution
Use an <abstract class> to share the unchangeable alignment flag and the rule that the reported length equals the rendered text's length. This small <class inheritance> hierarchy will also serve the numeric <software classes> in part (d). The <Java interface> explicitly declares `toString()` so that the display contract is visible even though all <Java> <software objects> already inherit that <object method>.
``
interface Data {
boolean leftJustified();
int length();
String toString();
}
abstract class AbstractData implements Data {
private final boolean leftj;
protected AbstractData(boolean leftj) { this.leftj = leftj; }
public final boolean leftJustified() { return leftj; }
public final int length() { return toString().length(); }
public abstract String toString();
}
final class StringData extends AbstractData {
private final String text;
public StringData(String s, boolean leftj) {
super(leftj);
if (s == null) throw new IllegalArgumentException("null text");
text = s;
}
public String toString() { return text; }
}
``
There are no setters, and the stored <String data type> value is an <immutable object>, so `StringData` is itself an <immutable object>. Its <object constructor> rejects a <null reference> instead of deferring failure until display. Consequently,
$$
\boxed{\texttt{length()}=\texttt{toString().length()},\qquad\text{alignment is fixed at construction}.}
$$
Back to article page