JAVA Programming Implement the toString method of the follow
JAVA Programming
Implement the toString method of the following version of theArrow class. Return strings such as
(Cannot change other part, only can work at \"Work Here\")
---------
Arrow.java
public class Arrow extends Point
{
private String direction;
/**
Constructs an arrow.
@param x the x-position
@param y the y-position
@param direction a compass direction N E S W NE NW SE SW
*/
public Arrow(int x, int y, String direction)
{
move(x, y);
this.direction = direction;
}
/**
Gets a string representation of this arrow.
@return the string representation such as (1, 2) NW
*/
public String toString()
{
----Work Here }
}
------------
Pointer.JAVA
public class Point
{
private int x;
private int y;
/**
Constructs a point at the origin.
*/
public Point()
{
this.x = 0;
this.y = 0;
}
/**
Moves this point by a given amount.
@param dx the x-distance
@param dy the y-distance
*/
public void move(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
/**
Gets a string representation of this point.
*/
public String toString()
{
return \"(\" + x + \", \" + y + \")\";
}
}
-----------
ArrowTester.java
public class ArrowTester
{
public static void main(String[] args)
{
Arrow arrow1 = new Arrow(1, 2, \"SE\");
System.out.println(arrow1);
System.out.println(\"Expected: (1, 2) SE\");
Arrow arrow2 = new Arrow(-1, 0, \"W\");
System.out.println(arrow2);
System.out.println(\"Expected: (-1, 0) W\");
}
}
Solution
Hi,
I have implemented the toString() method and highlighted the code changes below.
Arrow.java
public class Arrow extends Point
{
private String direction;
/**
Constructs an arrow.
@param x the x-position
@param y the y-position
@param direction a compass direction N E S W NE NW SE SW
*/
public Arrow(int x, int y, String direction)
{
move(x, y);
this.direction = direction;
}
/**
Gets a string representation of this arrow.
@return the string representation such as (1, 2) NW
*/
public String toString()
{
return super.toString()+\" \"+direction;
}
}
Point.java
public class Point
{
private int x;
private int y;
/**
Constructs a point at the origin.
*/
public Point()
{
this.x = 0;
this.y = 0;
}
/**
Moves this point by a given amount.
@param dx the x-distance
@param dy the y-distance
*/
public void move(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
/**
Gets a string representation of this point.
*/
public String toString()
{
return \"(\" + x + \", \" + y + \")\";
}
}
public class ArrowTester
{
public static void main(String[] args)
{
Arrow arrow1 = new Arrow(1, 2, \"SE\");
System.out.println(arrow1);
System.out.println(\"Expected: (1, 2) SE\");
Arrow arrow2 = new Arrow(-1, 0, \"W\");
System.out.println(arrow2);
System.out.println(\"Expected: (-1, 0) W\");
}
}
Output:
(1, 2) SE
Expected: (1, 2) SE
(-1, 0) W
Expected: (-1, 0) W


