我需要创建一个 add(Length) 方法,该方法返回一个新长度,其大小等于该长度和参数的大小之和。我不确定是否需要返回 double 或 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.
}
最佳答案
这取决于您的要求,但通常您希望返回一个新的 Length
对象。
public Length add(Length other){
// check that other is not null
return new Length(this.length + other.length);
}
您可以对所有其他数学方法执行类似的操作。
正如 Rohit 在他们的评论中所说,这使得你的类不可变,因为没有方法可以修改 length
字段(而是返回一个新的 Length
对象) 。
关于java - 在 ADT 中添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18643346/