0

我需要创建一个 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.

}
4

1 回答 1

1

这取决于您的要求,但通常您希望返回一个新Length对象。

public Length add(Length other){
    // check that other is not null
    return new Length(this.length + other.length);
}

你会为所有其他数学方法做类似的事情。

正如 Rohit 在他们的评论中所说,这使您的类不可变,因为没有可以修改该length字段的方法(而是返回一个新Length对象)。

于 2013-09-05T18:24:12.620 回答