comparing two objects with same parent abstract class and the output is zero

StackOverflow https://stackoverflow.com/questions/22129515

  •  19-10-2022
  •  | 
  •  

質問

i have an abstract class that implements comparable and has the following :

public abstract class Figure  implements Comparable{

    protected double height ;

    public abstract double getArea();   

    public abstract double calculatevolume();//will be used later to compare the volume

    public int compareTo(Figure o) {
        return 0;

    }   
}

i have circle and square as children of Figure but when i try to compare to volume of two objects it always return 0 !

this is my compareTo method in the circle class:

public int compareTo(Object o) {

    Figure a = (Figure) o;

    if (this.calculatevolume() > ((Figure) o).calculatevolume())
        return (int)this.calculatevolume();
    else if (this.calculatevolume() < ((Figure) o).calculatevolume())
        return (int) a.calculatevolume();

    else

    return 0;
}
役に立ちましたか?

解決

It should work better, but first please check your implementation of method calculatevolume weather that might return 0.

And please provide argument to comparable interface public abstract class Figure implements Comparable<Figure>

Figure circle = new Circle();
Figure square = new Square();
circle.compareTo(square);



public int compareTo(Figure a) {
        if (this.calculatevolume() > a.calculatevolume())
            return (int)this.calculatevolume();
        else if (this.calculatevolume() < a.calculatevolume())
            return (int) a.calculatevolume();
        return 0;
    }

他のヒント

You're using the raw version of the Comparable interface here

public abstract class Figure  implements Comparable{

In other words, you haven't provided a type argument to Comparable. As such, it expects a method declared as

public int compareTo(Object o) {

but your class is abstract so it doesn't complain. The method you provided

public int compareTo(Figure o) {

is completely unrelated to Comparable. You would see this if you annotated it with @Override.

In your child class, you provided

public int compareTo(Object o) {

which is the expected method (which overloads the paren'ts). But not the one you are calling.

You are probably using it as

Figure one = ...
Figure two = ...

one.compareTo(two);

Because the declared type of two is Figure, it will use the parent overloaded implementation which expects a Figure, and always returns 0.

A solution is to provide an appropriate type argument to Comparable.

public abstract class Figure  implements Comparable<Figure>{

and to work from there.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top