SE450: Types: Principle of Substitutivity [33/47] Previous pageContentsNext page

The Principle of Substitutivity (aka Liskov Substitution Principle): Subtypes should obey the behaviors expected by their supertypes.

Would it be okay if StringBuilder extended String?

void f(StringBuilder b, String s) {
  String t1 = new String(s);   // copy s
  String t2 = new String(s);   // copy s again
  Assert.assertEquals(t1,t2);  // t1 and t2 should be the same

StringBuilder b = new StringBuilder("cat");          

Would it be okay if String extended StringBuilder?

String s = new String();
StringBuilder b = s;
s.append(); // compiler error!  message not understood!

Some dubious interfaces:

Previous pageContentsNext page