繁体   English   中英

如果将子级添加为父级类,如何通过父级访问ArrayList中的子级对象?

[英]How can I access a child object in an ArrayList through a parent if I added the child as the parent class?

我正在研究一个需要使用Java类创建虚拟甜点商店的问题。 我需要打印某种以某种方式格式化的收据,并且我有圣代班。 我也有一个DessertItem类型的ArrayList(冰淇淋的超类,圣代的超类)。 我想从此arraylist访问Sundae中的方法,但是由于arraylist类型为DessertItem,所以它不允许我使用。 由于问题禁止,我无法更改ArrayList的类型。 由于问题禁止,我也无法编辑DessertItem类。 我已经尝试了很多事情,例如创建一个Sundae对象,并将DessertItem项目在数组列表中转换为Sundae并将其分配给该对象。 我相信这是因为当在Checkout类的enterItem方法中传递圣代对象时,它将作为IceCream对象传递。

(我把代码放在pastebin上,导致它无法正确格式化)

这是DessertItem类:

// DessertItem.java - Dessert Item abstract superclass


/**
 * Abstract superclass for Dessert Item hierarchy

 */
public abstract class DessertItem {

  protected String name;

/**
 * Null constructor for DessertItem class
 */
  public DessertItem() {
    this("");
  }
/**
 * Initializes DessertItem data
 */   
  public DessertItem(String name) {
    if (name.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)
      this.name = name;
    else 
      this.name = name.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);
  }
/**
 * Returns name of DessertItem
 * @return name of DessertItem
 */  
  public final String getName() {
    return name;
  }
/**
 * Returns cost of DessertItem
 * @return cost of DessertItem
 */  
  public abstract int getCost();

}

Checkout类(具有收据):

import java.util.ArrayList;

public class Checkout {

    ArrayList<DessertItem> dessertItems = new ArrayList<DessertItem>();

    public int cost;

    public Checkout() {
        // TODO Auto-generated constructor stub
    }

    public void clear() {
        dessertItems.clear();
    }

    public void enterItem(DessertItem item) {
        dessertItems.add(item);
    }

    public int numberOfItems() {
        return dessertItems.size();
    }

    @Override
    public String toString() {
        String reciept = "      " + DessertShoppe.STORE_NAME + "\n" +
                        "      --------------------\n" +
                        " \n";

        cost = 0;


        for (int i = 0; i < dessertItems.size(); i++) {
            if (dessertItems.get(i) instanceof IceCream) {
                reciept = reciept + " " + dessertItems.get(i).getName() + "       " + Integer.toString(dessertItems.get(i).getCost()) + "\n";
            } else if (dessertItems.get(i) instanceof Sundae) {
                reciept = reciept + (" Unfinished\n");
//              string.concat(" " + dessertItems.get(i).getName()).concat("       " + Integer.toString(dessertItems.get(i).getCost())).concat("\n");
            } else if (dessertItems.get(i) instanceof Candy) {
//              string.concat(" " + dessertItems.get(i).getName()).concat("       " + Integer.toString(dessertItems.get(i).getCost())).concat("\n");
            } else if (dessertItems.get(i) instanceof Cookie) {
                reciept = reciept + (" Unfinished\n");
//              string.concat(" " + dessertItems.get(i).getName()).concat("       " + Integer.toString(dessertItems.get(i).getCost())).concat("\n");
            }

            cost += dessertItems.get(i).getCost();
        }

        double taxRate = DessertShoppe.TAX_RATE;
        double tax = taxRate / 100;


        reciept.concat(" \n");
        reciept.concat(" Tax                         " + tax + "\n");
        reciept.concat(" Total Cost                " + (cost * (1 + tax)) + "\n");

        return reciept;
    }

    public int totalCost() {
        cost = 0;

        for (int i = 0; i < dessertItems.size(); i++) {
            cost += dessertItems.get(i).getCost();
        }

        return cost;
    }

    public int totalTax() {
        cost = 0;

        for (int i = 0; i < dessertItems.size(); i++) {
            cost += dessertItems.get(i).getCost();
        }
        double taxRate = DessertShoppe.TAX_RATE;
        double tax = taxRate / 100;

        return (int) Math.round(cost * tax);
    }
}

圣代班:

public class Sundae extends IceCream {

    public String toppingName;
    public int cost;
    public int toppingCost;

    public Sundae() {
        this("", 0, "", 0);
    }

    public Sundae(String newName, int newCost, String newToppingName, int newToppingCost) {
        if (newName.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)
            this.name = newName;
        else
            this.name = newName.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);

        if (newToppingName.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)
            this.toppingName = newToppingName;
        else
            this.toppingName = newToppingName.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);

        this.cost = newCost;
        this.toppingCost = newToppingCost;
    }

    @Override
    public int getCost() {
        return cost + toppingCost;
    }

    public String getToppingName() {
        return toppingName;
    }
}

请给我一个指示,因为我完全迷路了。

您是否尝试过投放到圣代?

((Sundae)(dessertItems.get(i))).getName()

遵循这些原则。 尽管我只是在相反的方向上尝试过,但这应该可以工作:将孩子抛弃给父母。

您可以在Oracle自己的多态性文档中阅读有关此内容的更多信息。

祝您项目顺利!

暂无
暂无

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

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