简体   繁体   English

如何在数组列表中显示对象的距离? (多态性)

[英]How to display an istanceof an object in an arraylist? (Polymorphism)

I am trying to display all of the elements in the ArrayList plantList. 我正在尝试显示ArrayList plantList中的所有元素。 My main program will add, delete, search, filter, and display all of the plants of four different child classes. 我的主程序将添加,删除,搜索,过滤和显示四个不同子类的所有工厂。 Everything "seems" to be working except when I display. 除了显示时,所有“似乎”都在工作。 ~I will only including portions of my code that are relevant to the questions. 〜我将只包括与问题相关的代码部分。

A little background: I am a student and this is my first time working with inheritance/polymorphism. 一点背景:我是一名学生,这是我第一次研究继承/多态性。

1)How do I distinguish between the different objects since they all have different parameters, at the time of displaying? 1)在显示时,由于它们都有不同的参数,如何区分不同的对象?

2) Any suggestions on how to improve the performance/logic of what I'm doing? 2)关于如何改善我正在执行的性能/逻辑的任何建议? A little explanation would be great. 稍微解释一下就好了。

//Parent class //父类

public class Plant{

   private String name;
   private String id;
   private String color;

   public Plant(String name, String id, String color){
   this.name = name;
   this.id = id;
   this.color = color;

   }

   public String getName(){

      return this.name;
   }

   public void setName(String name){

      name = this.name;  
   }

   public String getId(){

      return this.id;
   }

   public void setId(String id){

      id = this.id;  
   }

   public String getColor(){

      return this.color;
   }

   public void setColor(String color){
      color = this.color;  
   }


}

//one of several child classes //几个子类之一

   public class Flower extends Plant{

   private boolean thorns;
   private boolean smell;   

   public Flower(String name, String id, String color, boolean blnThorns, boolean blnSmell){
      super(name, id, color);
      thorns = blnThorns;
      smell = blnSmell;

   }

   public boolean isThorns(){

      return thorns;
   }

   public void setThorns(boolean blnThorns){
      thorns = blnThorns;  
   }

   public boolean isSmell(){

      return smell;
   }

   public void setSmell(boolean blnSmell){
      smell = blnSmell;  
   }


}

// portion of the main driver //主驱动程序的一部分

ArrayList<Plant> plantList = new ArrayList<Plant>();

//adding a flower to the plantList
System.out.println("\nEnter the name of the flower to add: ");
            name = add.nextLine();

            System.out.println("\nEnter the ID code: ");
            id = add.nextLine(); 

            System.out.println("\nEnter the color: ");
            color = add.nextLine();

            System.out.println("\nAre there thorns present? (True/False) ");
            blnThorns = add.nextBoolean();

            System.out.println("\nDoes the flower smell? (True/False) ");
            blnSmell = add.nextBoolean();

            plantList.add(new Flower(name, id, color, blnThorns, blnSmell));

            System.out.println("Flower inserted.");
            System.out.println();
            break;

//displaying all plants
for( int i = 0; i < plantList.size(); i++){
      System. out.println("\t" + (i+1) + ":");
            System.out.print("\n\tName: " + plantList.get(i).getName());
            System.out.print("\n\tName: " + plantList.get(i).getId());
            System.out.print("\n\tColor: " + plantList.get(i).getColor());
            if(plantList instanceof Flower){ // HERE I am not sure what I'm doing or how to do it
            System.out.print("\n\tThorns presence: " + plantList.get(i).isThorns()); /* this is an example of what is not working properly */
            System.out.print("\n\tSmell presence: " + plantList.get(i).isSmell());  /* this is an example of what is not working properly*/
            System.out.println("\n");
            }
         }

If by "display" you mean "print some sort of string to the console or other output", then the answer is fairly simple: there's no need to use instanceof at all. 如果用“显示”来表示“将某种字符串打印到控制台或其他输出上”,那么答案就很简单:根本不需要使用instanceof All you need to do is override the toString method in each different class that you want to be displayable, then when you want to display an object (even if you don't know exactly what type it is), just call toString on it and print the result. 您需要做的就是在要显示的每个不同类中重写toString方法,然后在要显示对象时(即使您不确切知道它是什么类型),只需在其上调用toString 。打印结果。 Polymorphism will do the job of picking which toString method implementation to call. 多态性会做采摘的工作toString调用方法实现。

Here's how it would look in your specific example. 这是您的特定示例中的外观。

In the Plant class: 在Plant类中:

@Override
public String toString() {
   return "\n\tName: " + getName()
        + "\n\tName: " + getId()
        + "\n\tColor: " + getColor();
}

Then, in the Flower class: 然后,在Flower类中:

@Override
public String toString() {
   return super.toString()
        + "\n\tThorns presence: " + isThorns()
        + "\n\tSmell presence: " + isSmell();
}

Finally, to display all plants: 最后,显示所有植物:

for (Plant plant : plantList) {
   System.out.println(plant);
}

Note that toString is called automatically when you pass any Object to System.out.println . 请注意,当您将任何Object传递给System.out.println时, toString会自动调用。

You were really close. 你真的很亲近 You just needed to check against the element of the list, not the list itself, when you did the instanceof check. 在执行instanceof检查时,您只需要检查列表的元素 ,而不是列表本身。 Then, if it is in fact an instance of Flower , then you need to cast the list element to a Flower and make the method calls from there. 然后,如果实际上是Flower的实例,则需要将list元素转换为Flower并从那里进行方法调用。

Like this: 像这样:

for(int i = 0; i < plantList.size(); i++){
    System.out.println("\t" + (i+1) + ":");
    System.out.print("\n\tName: " + plantList.get(i).getName());
    System.out.print("\n\tName: " + plantList.get(i).getId());
    System.out.print("\n\tColor: " + plantList.get(i).getColor());
    if (plantList.get(i) instanceof Flower) {
        Flower flower = (Flower)plantList.get(i);
        System.out.print("\n\tThorns presence: " + flower.isThorns());
        System.out.print("\n\tSmell presence: " + flower.isSmell());
        System.out.println("\n");
    }
}

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

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