forum

Home / DeveloperSection / Forums / How to return different values toString?

How to return different values toString?

Royce Roy162705-Nov-2014
I'm pretty new in java and I'm doing a simple program but I don't know why I get different values, i.e., if I use getX, getY and getZ I get (6,5,8) but if I use toString I get different values for X and Y (3, 4, 8), so can anyone explain me why it happens because as far as I understand it should get the same values in both cases or what I'm doing wrong?

publicclassCoordinates {
 
    privatedouble coorX, coorY;
 
    Coordinates()
    {
        coorX = 1;
        coorY = 1;
    }
 
    Coordinates(double x, double y)
    {
        coorX = x;
        coorY = y;     
    }
 
    void setX(double x)
    {
        coorX = x;
    }
 
    void setY(double y)
    {
        coorY = y;
    }
 
    double getX()
    {
        return coorX;
    }
 
    double getY()
    {
        return coorY;
    }
 
    publicString toString()
    {
        String myString = "(" + coorX + " , " + coorY + ")";
        return myString;
    }
 
    publicclassCoordinates3D extends Coordinates{
        privatedouble coorZ;
 
        Coordinates3D()
        {
            super();
            coorZ = 1;
        }
 
        Coordinates3D(double x, double y, double z)
        {
            super(x,y);
            coorZ = z;
        }
 
        publicvoid setZ(double z)
        {
            coorZ = z;
        }
 
        double getZ()
        {
            return coorZ;
        }
 
        @Override
        publicString toString()
        {
            String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
            return myString;
 
        }
 
    }
 
 
    /**
     * @param args
     */
    publicstaticvoid main(String[] args) {
        // TODO Auto-generated method stub
 
        Coordinates test1 = newCoordinates(3,4);
 
 
        System.out.println(test1.toString());
 
        System.out.println(test1.getX());
        System.out.println(test1.getY());
 
 
        Coordinates3D test2 = test1.newCoordinates3D(6,5,8);
 
        System.out.println(test2.toString()); ---> here is the problem
 
        System.out.println(test2.getX());
        System.out.println(test2.getY());
        System.out.println(test2.getZ());
 
 
    }
 
}


Updated on 05-Nov-2014

Can you answer this question?


Answer

1 Answers

Liked By