doesn't this make polymorphism useless (6)

1 Name: x : 2010-06-29 05:48 ID:bj54dl61

Hey all.

Say I have parent class Bicycle (this is in Java if you care) and it has children classes RoadBike and MountainBike.

Say I did this...

//=====================================================
public class TestBikes {
public static void main(String[] args){

Bicycle bike01, bike02, bike03;
bike01 = new Bicycle(20, 10, 1);
bike02 = new MountainBike(20, 10, 5, "Dual");
bike03 = new RoadBike(40, 20, 8, 23);
bike01.printDescription();
bike02.printDescription();
bike03.printDescription();

}
}
//=====================================================

...How is that any different than just making bike01, bike02, and bike03 their own respective types (instead of all Bicycle) and calling each unique object's printDescription() method?

2 Name: #!/usr/bin/anonymous : 2010-06-30 19:31 ID:ZljKLK1n

Indeed, in this case you don't need polymorphism. But you need it when you write something like this:
//===
Bicycle bike;

if (condition)
bike = new MountainBike(20, 10, 5, "Dual");
else
bike = new RoadBike(40, 20, 8, 23);

...

bike.printDescription();
//===

3 Name: #!/usr/bin/anonymous : 2010-06-30 22:58 ID:nTCRGN+u

Polymorphism is useful when the function, program, programmer, etc, has agreed on a set of functions for some behavior, but does not care for the identity of the object itself.

4 Name: #!/usr/bin/anonymous : 2010-07-07 17:24 ID:rHL6hpwO

The printDescription() method of the base Bicycle could print some information like say, the price.
When you make the printDescription() of the Child objects, you could make it call the printDescription() of the parent, so that you don't have to print the price again.

That's the goal of polymorphism, making thing easier to modify and give more sense to the semantics

5 Name: #!/usr/bin/anonymous : 2010-08-12 09:50 ID:V5d1thiu

YOU ARE COMPLETELY CORRECT. THIS MAKES POLYMORPHISM USELESS. I JUST SENT A LETTER TO ORACLE TO INFORM THEM OF THIS, AND IT SHOULD BE REMOVED FROM THE NEXT VERSION OF JAVA.

6 Name: #!/usr/bin/anonymous : 2010-08-14 12:06 ID:BEdbUVEM

>>1
In your example, it's useless. But if you had an example like this:

void doSomethingWithBike(Bicycle bike) {
bike.move(12);
bike.printDescription();
}

you can doSomething with all kind of bikes. The point of polymorphism is to allow methods to "don't give a fuck" about the objets they are manipulating. It's not for you, it's for the code.

This thread has been closed. You cannot post in this thread any longer.