javainheritancescopecartesian

Do you inherit an object of super class in base class when you inherit it?


I have this class which basically represents a point in X-Y plane and has this function to calculate distance between two Point Objects:

double dist(2DPoint p){
return Math.sqrt(Math.pow(x-p.x, 2) + Math.pow(y-p.y, 2));
}

I now want to create a class that represents a point in space in a class 3DPoint. I want to inherit 2d Point and create a function which calculates distance between two 3d points.

I want to do it in such a way that I could use the previous function like this:

double dist(3DPoint p)
{
    return Math.sqrt(Math.pow(z - p.z, 2) + /*Square of dist between X,Y s of the two 3d pts using the dist function from 2DPoint*/);

}


Solution

  • Try this.

    class Point2D {
        double x, y;
        double dist(Point2D p) {
            return Math.hypot(x - p.x, y - p.y);
        }
    }
    
    class Point3D extends Point2D {
        double z;
        double dist(Point3D p) {
            return Math.hypot(z - p.z, super.dist(p));
        }
    }