我需要创建一个add(Length)方法,该方法返回一个大小相等的新长度,该长度与该长度和参数的大小之和相等。我不确定是否需要返回双精度或长度以及如何添加
public class Length implements Comparable<Length>{
private final double length; //private! Do NOT add a getter
// This constructor must remain private
private Length(double l){
length = l;
}
public double add(Length l){
return ;
}
public double subtract(Length l){
}
public double scale(double d){
}
public double divide(Length l){
}
public double Length(Position one, Position two){
}
// TODO: For all constants, have a line:
// public static final Length ... = new Length(...);
// Use the @Override annotation on all methods
// That override a superclass method.
@Override
public boolean equals(Object other){
//TODO
}
@Override
public int hashCode(){
//TODO
}
@Override
public String toString(){
//TODO
}
// If you are overriding a method from an interface, then Java 5
// says you CANNOT use Override, but Java 6 says you MAY. Either is OK.
// @Override
public int compareTo(Length other) {
//TODO
}
// TODO Write the rest of the methods for this class, and
// the other two classes.
}
答案 0 :(得分:1)
这取决于您的要求,但通常您需要返回一个新的Length
对象。
public Length add(Length other){
// check that other is not null
return new Length(this.length + other.length);
}
你会为所有其他数学方法做类似的事情。
正如Rohit在评论中所说,这使得你的类不可变,因为没有方法可以修改length
字段(而是返回一个新的Length
对象)。