forum

home / developersection / forums / how to return different values tostring?

How to return different values toString?

Royce Roy 1886 05-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?

public class Coordinates {
 
    private double 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;
    }
 
    public String toString()
    {
        String myString = "(" + coorX + " , " + coorY + ")";
        return myString;
    }
 
    public class Coordinates3D extends Coordinates{
        private double coorZ;
 
        Coordinates3D()
        {
            super();
            coorZ = 1;
        }
 
        Coordinates3D(double x, double y, double z)
        {
            super(x,y);
            coorZ = z;
        }
 
        public void setZ(double z)
        {
            coorZ = z;
        }
 
        double getZ()
        {
            return coorZ;
        }
 
        @Override
        public String toString()
        {
            String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
            return myString;
 
        }
 
    }
 
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
 
        Coordinates test1 = new Coordinates(3,4);
 
 
        System.out.println(test1.toString());
 
        System.out.println(test1.getX());
        System.out.println(test1.getY());
 
 
        Coordinates3D test2 = test1.new Coordinates3D(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
Royce Roy

Other


Message
Can you answer this question?

Answer

1 Answers

Liked By