In your example, it doesn't matter which way you chose. Your example doesn't show the power of polymorphism.
Let's see a trivial example of Polymorphism:

interface Shape{
void draw();
}
class Rectangle implements Shape{
public void draw(){
System.out.println("Drawing Rectangle.");
}
}
class Triangle implements Shape{
public void draw(){
System.out.println("Drawing Triangle.");
}
}
class Circle implements Shape{
public void draw(){
System.out.println("Drawing Circle.");
}
}
Rectangle
, Triangle
, and Circle
are just implementing their own definition of draw
function.
Now, suppose you've to implement a drawAllShapes
method in your Main
class, which takes a bunch of shapes and print them all. But without polymorphism this can be hectic, as there can be different types of shapes. Now, here comes polymorphism to save us.
class RandomShapeFactory{
public static Shape createRandomShape(){
Shape randomShape;
Random random = new Random();
int randomNo = random.nextInt() % 3 + 1;
if (randomNo == 1){
randomShape = new Rectangle();
}
else if (randomNo == 2){
randomShape = new Triangle();
}
else{
randomShape = new Circle();
}
return randomShape;
}
}
class Main{
public static void main(String[] args){
Shape[] shapes = new Shape[10];
for (int i = 0; i < shapes.length; i++){
shapes[i] = RandomShapeFactory.createRandomShape();
}
drawAllShapes(shapes);
}
public static void drawAllShapes(Shape[] shapes){
for (int i = 0; i < shapes.length; i++){
shapes[i].draw();
}
}
}
This implementation of drawAllShapes
doesn't have to know whether the Shape
at index i
is a Circle
or Triangle
or what, whichever Shape
it is, it just calls their implementation of the draw
method.
main
method has all random shapes, and when passed to the drawAllShapes
method, their relative implementations are invoked.
This kind of implementation also follows the Open/Closed Principle, that if you want, in future, to add some more Shapes to the hierarchy, drawAllShapes
method doesn't have to know about the new shapes either, just add new classes and implement the Shape
interface, and drawAllShapes
will work with those shapes too.
See the above example in action here.