Polymorphism

Topic Progress

Polymorphism is the programming language’s ability to process objects differently. In the example below there is the “Car” base class that has the method “move”, other cars such as Honda and Mazda can process the method move in their own particular way. They can override it so the method move has many forms (polymorphism)

  • Poly: means many
  • Morphism: means forms

You will need to set up an Eclipse or Netbeans project as below:


1
2
3
4
5
6
7
8
9
10
11
public class Car {

    int price;
    String name;
    String color;

    public void move(){
    System.out.println("Basic Car move");
    }

}
1
2
3
4
5
public class Ford extends Car{
  public void move(){
    System.out.println("Moving with V engine");
  }
}
1
2
3
4
5
public class Honda extends Car{
  public void move(){
    System.out.println("Move with i-VTEC engine");
  }
}
1
2
3
4
5
public class Mazda extends Car{
  public void move(){
    System.out.println("Move Mazda Engine");
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class PolyMorphismExample {
  public static void main(String[] args) {
    Car car = new Car();
    Car f = new Ford();
    Car h = new Honda();
    Car m = new Mazda();

    car.move();
    f.move();
    h.move();
    m.move();

  }
}

Extension

  • Add another car E.g Ferrari
  • Add a method accellerate
  • Change the PolyMorphismExample file to output accelerate