Search My Blog

Wednesday, June 27, 2012

runtime polymorphism using interfaces in Java


(Source - Stack overflow)

Interfaces allow you to use classes across different hierarchies polymorphically.

For example, say you have the following interface:
public interface Movable {
    void move();
}
 
Any number of classes, across class hierarchies could implement Movable in their own specific way, yet still be used by some caller in a uniform way.

So if you have the following two classes:

public class Car extends Vehicle implements Movable {
    public void move() {
       //implement move, vroom, vroom!
    }
}
public class Horse extends Animal implements Movable {
    public void move() {
       //implement move, neigh!
    }
}

From the perspective of the caller, it's just a Movable
 
Movable movable = ...;
movable.move();  //who am I?

No comments:

Post a Comment