【发布时间】:2014-05-26 23:59:28
【问题描述】:
我应该编写一个实现Locatable 接口的Cruiser 类。 Cruiser 将具有 x、y 和速度属性。 x、y 和速度是整数。您必须为 Cruiser 类提供 3 个构造函数。 Cruiser 类必须实现Locatable 接口。
一个构造函数必须是默认的。一个构造函数必须是仅 x 和 y 构造函数。一个构造函数必须是 x、y 和 speed 构造函数。您必须提供一个 equals 方法。 equals() 方法应该比较两个 Cruiser 对象的属性。您必须提供一个 toString() 方法。 toString() 应该返回 Cruiser 的 x、y 和速度。
当我编译它时它说“类 Cruiser 是公共的,应该在 Cruiser.java 中声明”
当我这样做时,我的 IDE 会显示“;”正如在公共布尔等于之后所预期的那样。但这没有意义,为什么您需要在方法中使用分号。
这就是我目前所拥有的
public interface Locatable
{
public int getxPos();
public int getyPos();
}
public class Cruiser implements Locatable
{
private int xPos, yPos, speed;
public Cruiser()
{
xPos=yPos=speed=0;
}
public Cruiser(int x,int y)
{
xPos=x;
yPos=y;
speed=0;
}
public Cruiser(int x, int y, int spd)
{
xPos=x;
yPos=y;
speed=spd;
}
public int getxPos()
{
return xPos;
}
public int getyPos()
{
return yPos;
}
public int getSpeed()
{
return speed;
}
public void compare(Cruiser A, Cruiser B)
{
@Override
public boolean equals(Object obj)
{
if (obj instanceof Cruiser) {
Cruiser cruiserToCompareTo = (Cruiser)obj;
if(xPos == cruiserToCompareTo.getXpos() &&
yPos == cruiserToCompareTo.getYpos() &&
speed == cruiserToCompareTo.getSpeed())
return true;
}
return false;
}
public String toString()
{
String properties = "X position:"+ xPos+ ", Y position:"+yPos+ ",Speed:"+speed;
return properties;
}
}
}
【问题讨论】:
-
您能花时间正确对齐您的代码吗?这使我们更容易阅读。在 Eclipse 或 Netbeans 等 IDE 中,您只需单击几下即可完成此操作。
标签: java oop interface constructor compare