Polymorphism through Interfaces
With Examples in Java |
Prof. David Bernstein
|
Computer Science Department |
bernstdh@jmu.edu |
Person
"is a" Ordered
)
public interface Ordered {...}
public interface Animated {...}
public class Versatile implements Ordered, Animated {...}
Animated a = new Animated();
Animated a = new Versatile();
Ordered o = new Animated();
Ordered o = new Ordered();
Ordered o = new Versatile();
o.compareTo(p);
v.compareTo(w);
o.compareTo(v);
public interface Ordered {...}
public interface Animated {...}
public class Versatile implements Ordered, Animated {...}
public void add(Animated item) {...}
public void add(Ordered item) {...}
public void add(Versatile item) {...}
add()
is passed a Versatile
that is declared to be a Versatile
?add(Versatile item)
is executed
add()
is passed a Versatile
that is declared to be an Animated
?add(Animated item)
is executed
add()
is passed a Versatile
that is declared to be a Ordered
?add(Ordered item)
is executed
public void add(Animated item) {...}
public void add(Ordered item) {...}
add()
is passed a Versatile
that is declared to be a Versatile
?add()
is
determined to be ambiguous (hence the statement won't compile)
add()
is passed a Versatile
that is declared to be an Animated
?add(Animated item)
is executed
add()
is passed a Versatile
that is declared to be a Ordered
?add(Ordered item)
is executed