Skip to main content

Why doesn't Segment#subSequence() return a Segment?

3 replies [Last post]
uncle_alice
Offline
Joined: 2003-06-16

As of JDK 6, javax.swing.text.Segment implements the CharSequence interface, but its subSequence() method has CharSequence as its return type. Why not take advantage of covariant return types and have it return a Segment instead? I've been doing that in my own SegmentCharSequence class for several months now.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
forax
Offline
Joined: 2004-10-07

And imagine a programmer that subclass Segment and
without knowing the CharSequence interface
decides to add a method subSequence that returns an int.

class Mygment extends Segment {
public int subSequence() {
return 0;
}
}

This code will compile with 1.5 but not with 1.6.

jansan, adding a method potentially breaks the backward
compatibility.

jansan
Offline
Joined: 2005-02-24

Very simple, because it would potentially break backward compatibility. Imagine a programmer has subclassed Segment and he/she decided for some bizarre reason to override subSequence() and return an instance of String. If Sun changed the return type of subSequence() to Sequence, the programmer's class would not work anymore.

uncle_alice
Offline
Joined: 2003-06-16

Come to think of, it would probably break [i]my[/i] code. I wouldn't mind, since I only use that class in a hobby project, but I suppose others might. :D