Help on polymorphism in my code
Hi, I'd be glad if anyone could explain why java compiler gives errors
compiling a class of a simple application.
This is the scenario: class Point is meant to simplicistically abstract the
concept of 2D point (x and y are the coordinates). Class Point3D extends Point,
adding z coordinate. Attributes x, y and z are encapsulated (private and each
one with setter and getter methods).
There is a third class, called Ruler, its aim is to set the distance between
two 2D points or two 3D points using the polymorphic method
computeDistance(Point p1, Point p2).
The compiler fails compiling the class Ruler with this message:
Ruler.java:21: p1 is already defined in computeDistance(Point,Point)
Point3D p1 = (Point3D) p1;
^
Ruler.java:22: p2 is already defined in computeDistance(Point,Point)
Point3D p2 = (Point3D) p2;
^
2 errors
This is the relevant part of the class:
publicclass Ruler
{
privatedouble distance;
publicvoid computeDistance(Point p1, Point p2)
{
if (p1instanceof Point && p2instanceof Point)
{
// This is a 2D points case.
// Obtain x1, x2, y1, y2 via getX() and getY() then compute the
// distance.
// .....
}
elseif (p1instanceof Point3D && p2instanceof Point3D)
{
// This is a 3D points case.
// Obtain x1, x2, y1, y2, z1, z2 using getX() and getY(), getZ().
// BUT, in order to obtain z1, z2 it is needed a casting between
// objects, because Point objects don't provide getZ(), while
// Point3D do.
Point3D p1 = (Point3D) p1;
Point3D p2 = (Point3D) p2;
// ....
}
else
{
// This case is not valid.
}
}
}
If this piece of code is not enough I'll write in another post all the three
classes exactly as they are.
Thanks for any help!

