The clearest way to express polymorphism is via an abstract base class (or interface)
public abstract class Bicycle
{
...
public abstract void ride();
}
This class is abstract because the ride() method is not defined for Bicycle. It will be defined for the subclasses RoadBike and MountainBike. Also, Bicycle is an abstract concept . It’s got to be one or the other.
So we defer the implementation by using the abstract class.
public class RoadBike extends Bicycle
{
...
@Override
public void ride()
{
System.out.println("RoadBike");
}
}
and
public class MountainBike extends Bicycle
{
...
@Override
public void ride()
{
System.out.println("MountainBike");
}
}
Now we can difference by calling Bicycle at runtime base class Bicycle but due to run time binding respective subclass methods will be invoked .
public static void main(String args)
{
ArrayList<Bicycle> group = new ArrayList<Bicycle>();
group.add(new RoadBike());
group.add(new MountainBike());
// ... add more...
// tell the class to take a pee break
for (Bicycle bicycle : group) bicycle.ride();
}
Running this would yield:
RoadBike
MountainBike
...
Hope this will clear you what the difference is !