繁体   English   中英

比较扩展对象

[英]comparing extended objects

private List<Fruit> myFruit = new Vector<Fruit>();

好的,如果我有一个不同类型的水果对象的列表,该如何浏览该列表并比较不同的对象。

public class Fruit{
 String type;
 String color;

 }

 public class Grape extends Fruit{
  int seedCount;

   public Grape(Attributes attributes){
    this.type = attributes.getValue("type");
    this.color=attributes.getValue("color");
    this.seedCount=attributes.getValue("seedCount");

 }

 public class Banana extends Fruit{
    String color;

   public Banana(Attributes attributes){
    this.type = attributes.getValue("type");
    this.color=attributes.getValue("color");


 }


public load(localName name, Attributes attributes){
if (name.equalsIgnoreCase("grape"){
 Grape grape = new Grape(attributes);
 myFruit.add(grape);
  }
if (name.equalsIgnoreCase("banana"){
   Banana banana = new Banana(attributes);
   myFruit.add(banana);
  }
 }

因此,我将如何对Fruit列表进行排序,并根据对象的类型显示这些对象的特定属性。 就是 如果type = Grape,则显示seedCount。

  1. 如果要对Fruit进行排序,则需要为Fruit类实现Comparable接口。

  2. 如果要显示属性,请在Fruit类中使用抽象方法,并在子类中提供实现。 这种方式取决于Fruit的实例,它将显示相应的属性。

    公共抽象类Fruit实施Comparable {

      public abstract void displayProperties(); @Override public int compareTo(Fruit otherFruit){ return 0; } } public class Banana extends Fruit { private int seedCount; @Override public void displayProperties() { // TODO Auto-generated method stub System.out.println(seedCount); } } public class Grape extends Fruit{ private String color; @Override public void displayProperties() { // TODO Auto-generated method stub System.out.println(color); } } 

您可以向Fruit displayProperties()添加抽象方法

然后,您将不得不对所有类型的水果隐含该方法,然后在for循环中,只需调用displayProperties()

不建议这样做,但是您可以使用

if(object instanceof Class) {
    Class temp = (Class) object
    //operate on object
}

但是您应该做的是创建一个Fruit界面,该界面可以访问与所有水果相关的重要信息,通常,您不应该为了获得更多信息而放弃。

虽然垂头丧气不是邪恶的,但这可能意味着您没有充分利用多态性。 要利用多态性,应确保子类型共享的超类型具有获取所需信息或行为的方法。

例如,假设您有一个HousePets列表,并且HousePets由子类型Dog和Cat组成。 您遍历此列表,并想要摇晃HousePets可以拖尾的所有尾巴。 为简单起见,有两种方法可以执行此操作,或者仅Dog具有方法“ wagTail()”(因为Cats不会摇尾巴),或HousePets具有Cat's and Dogs继承的名为“ wagTail()”的方法(但Cat的版本不执行任何操作)。 如果选择第一个示例,则代码将如下所示:

 for(HousePet pet : petList)
     if(pet instanceof Dog) {
         ((Dog)pet).wagTail();
     }

对于第二个示例,它看起来像这样:

 for(HousePet pet : petList)
     pet.wagTail();

第二个示例少了一些代码,但简化了一些。 在最坏的情况下,如果我们选择第一个选项,则将为HousePet的每个新子类型需要一个if块,这将使代码更笨重/更丑陋/等。 更好的是,我们可以有一个称为“ showHappiness”的HousePet方法,当猫发出呼pur声时,狗会摇尾巴。

我认为您需要一个instanceof运算符。 它允许您检查对象类型。

if (list.get(0) instanceof Grape) {
    // list.get(0) is Grape
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM