I know how to put value from one class to another. Just here it doesn't work. I can't understand why.
Please help me to find a bug.
When I try to get value:
c = new CartesianCoordinate(x, y);
x = c.getX();
It is always zero.
public class Velocity
{
// instance variables - replace the example below with your own
private double x;
private double y;
/**
* Constructor for objects of class Velocity
*/
public Velocity(CartesianCoordinate c)
{
// initialise instance variables
c = new CartesianCoordinate(x,y);
x = c.getX();
System.out.println(c.getX());
System.out.println(c.getY());
System.out.println(c.x);
}
public double getX()
{
return x;
}
Here is my CartesianCoordinate:
public class CartesianCoordinate
{
// instance variables - replace the example below with your own
public double x;
public double y;
/**
* Constructor for objects of class CartesianCoordinate
*/
public CartesianCoordinate(double x, double y)
{
// initialise instance variables
this.x = x;
this.y = y;
}
public void setX(double x)
{
// put your code here
this.x = x;
}
public void setY(double y)
{
this.y = y;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
}
In following line:
c = new CartesianCoordinate(x,y);
you are creating a new instance with the values of Velocity
instance private fields x
and y
, which are set to 0 by default.
By the way, it makes no sense to pass a CartesianCoordinate
instance as the constructor parameter, then re-initialising it inside the constructor itself. Either you pass x
and y
values like public Velocity(int x, int y)
, or you just assign the coordinate.
In the future, you'll want to know about Point2D
class.