2

Problem:

1) I want to do collection.sort. The problem is inside the " public int compareTo (Fruit other)" i would like to sort the taste and smell in alphabetical order, but, i don't know how to pass the subclass value to superclass and use "this & other " comparison. Thanks for help

PS: The code is simplified , just want to know the way to do the sorting from subclass parameter only.

Here is the code:

public class Fruit implements Comparable<Fruit>{

protected String Type;
protected int price;

public Fruit(String Type , int Price)
{
    this.Type = Type;
    this.price = Price;

}
public int compareTo (Fruit other)
{
    if (this.Type.compareTo(other.Type) != 0)
    {
        return (this.Type.compareTo(other.Type));
    }
    else if (Integer.compare(this.price,  other.price)!=0)
    {
        return (Integer.compare(this.price,  other.price));
    }
    //else if (  ** If price is same , then get sorting with taste 
    in  alphabetical order **) //
    {
    }
    //else if (  ** if taste is the same , then get sorting with smell
    in alphabetical order **) //
    {
    }
    else 
    {
        return 0;
    }
}




 public class orange extends Fruit()
 { 
 private String taste;
 private String smell; 
 public orange (String Type , int Price , String taste , String smell)
 {
    super (Type, Price);
    this.taste = taste;
    this.smell = smell;
 }

 } 
Kindess
  • 49
  • 6

1 Answers1

0

Test the class inside the compareTo:

  • if it is your subclass

  • and the other object too

  • cast them, and compare with your sub-test

Suppose:

public class Kiwi extends Fruit 
   {
   public String taste;  // public for demo
   public String smell;
   }

Test and cast:

Fruit one_fruit;  // this or other
if (one_fruit instanceof Kiwi) 
    {
    Kiwi really_kiwi= (Kiwi) one_fruit; // CAST THERE !
    if (really_kiwi.taste ...) // You can then use taste and smell ...