【问题标题】:Subclasses and Superclasses子类和超类
【发布时间】:2014-03-23 22:35:25
【问题描述】:

我正在尝试构建一个具有某些要求的程序,主要是我有一个类,然后创建一个添加功能的子类。我创建类 DVD,然后创建子类。

我正在添加一种将年份添加到列表中的方法,以及将添加到打印的最终库存价值的进货费用。我构建了子类,创建了覆盖方法,但它没有被添加到显示的输出中。不仅如此,它还把输入年份放在了错误的位置。我没有收到任何错误,它就像子类不存在一样,即使我的 DVD 类说某些方法正在被覆盖。

我想我一定是遗漏了一些我应该调用新方法的地方,也许我读错了资源,但听起来我只需要调用 DVD 类,而我想要覆盖的方法会被自动覆盖。我更愿意将此信息添加到超类中,但这是分配的要求。

所以我想知道,当我需要这些覆盖方法来添加这些新功能时,我实际上应该如何调用它们?我不断看到资源告诉我如何创建它们,但实际上并没有实现它们。

从我的 main 方法中,我调用 dvd 类然后打印它。但是,它只打印原始 dvd 类中的内容,除了将年份添加到产品 ID 应该是的奇怪添加。

public class DVD {



String name;
int id;
int items;
double cost;

//default constructor
public DVD() {
    name = "";
    id = 0;
    items = 0;
    cost = 0.0;
}//end default constructor

//constructor to initialize object
public DVD(String dvdName, int itemNum, int quantity, double price) {
    name = dvdName;
    id = itemNum;
    items = quantity;
    cost =  price;
}//end constructor


//method to calculate value
public double getInventoryValue() {
       return items * cost;
}

//method to set name
public void setdvdName(String dvdName){
    this.name = dvdName;
}

//method to get name
public String getName(){
    return name;
}

//method to set id
public void setitemNum( int itemNum){
    this.id = itemNum;
}

//method to get id
public int getId(){
    return id;
}

//method to set items
public void setquantity(int quantity){
    this.items = quantity;   
}

//method to get items
public int getItems(){
    return items;
}

//method to set cost
public void setprice( double price){
    this.cost = price;
}

//method to get cost
public double getCost(){
    return cost;
}

/**
 *
 * @return
 */

public String toString() {

    return "DVD Name: " + getName() +
           "ID: " + getId() +
           "Items: " + getItems() +
           "Cost: " + getCost() + 
           "Total Value: " +getInventoryValue();
}
}

-

public class ExtendedDVD extends DVD{
double restockFee;
int year;

public ExtendedDVD(){
    year = 0;
}
public ExtendedDVD(int year) {
    this.year = year;
}

public void setRestockFee(){
    this.restockFee = 0.05;
}

public double getRestockFee(){
    return restockFee;
}


public void setYear(){
    this.year = 0;
}

public int getYear(){
    return year;
}

@Override
public double getInventoryValue(){
    double value1 = super.getInventoryValue();
    double value = restockFee * value1;
    double totalInventoryValue = value + super.getInventoryValue();
    return totalInventoryValue;
}

@Override
 public String toString(){
    return super.toString() + "Year" + getYear();
}
}

}

public class Inventory {

DVD[] inventory = new DVD[5];
int current = 0;
private int len;

public Inventory(int len){
    inventory = new DVD[len];

}

public double calculateTotalInventory() {
    double totalValue = 0;
    for ( int j = 0; j < inventory.length; j++ ) 
        totalValue += inventory[j].getInventoryValue();
    return totalValue;
}

/**
 *
 * @param dvd
 * @throws Exception
 */
public void addDVD(DVD dvd) throws Exception {
    if (current < inventory.length) {
        inventory[current++]=dvd;
    }else {
        Exception myException = new Exception();
        throw myException;

    }
    }
void sort() {
      for (DVD inventory1 : inventory) {
        len = current;
    }

      for (int i=0; i<len;i++) {
        for(int j=i;j<len;j++) {
            if (inventory[i].getName().compareTo(inventory[j].getName())>0) {
                DVD temp = inventory[j];
                inventory[j] = inventory[i];
                inventory[i] = temp;
            }
        }
    }
}




  public int getNumberOfItems() {
    return current;
}


    public void printInventory() {
    System.out.println("Current Inventory:");
    for(int i=0;i<current;i++) {
        System.out.println(inventory[i]);
    }
    System.out.println("The total value of the inventory is:"+calculateTotalInventory());
    }
}

-

public class inventoryprogram1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args){


    boolean finish = false;
    String dvdName;
    int itemNum;
    int quantity;
    double price;
    int year = 0;

    Inventory inventory = new Inventory(5);
    while (!finish) {
        Scanner input = new Scanner(System.in); // Initialize the scanner
        System.out.print("Please enter name of DVD: ");
        dvdName = input.nextLine();
        if (dvdName.equals("stop")) {
            System.out.println("Exiting Program");
            break;
        } else {
            System.out.print("Please enter Product Number: ");
            itemNum = input.nextInt();
            System.out.print("Please enter units: ");
            quantity = input.nextInt();
            System.out.print("Please enter price of DVD: ");
            price = input.nextDouble();
            System.out.print("Please enter production year: ");
            itemNum = input.nextInt();

            DVD dvd= new DVD(dvdName,itemNum,quantity,price);

            try {
              inventory.addDVD(dvd);
            }catch( Exception e) {
                System.out.println("Inventory is full.");
                break;
            }

            System.out.println("DVD: " + dvd);

        }//end else

    }
       inventory.sort();
       inventory.printInventory();
}
}

【问题讨论】:

  • 如果您从不创建任何 ExtendedDVD,那么很明显,ExtendedDVD 类的任何方法都不会被调用。

标签: java inheritance subclass superclass


【解决方案1】:

如果您想使用您在 ExtendedDVD 中编写的新方法,您需要实例化该类,您仍然调用原始 dvd 类,这样您仍然可以获得这些方法。

例如

DVD dvd = new DVD(dvdName, itemNum, quantity, price);

DVD Dvd = new ExtendedDVD(dvdName, itemNum, quantity, price);

是两个不同的东西

如果你查看你的 main 方法,你会分配 itemNum 两次,这就是它显示年份的原因

【讨论】:

  • 感谢您了解这一点,我复制了一些行以加快速度,但完全错过了这一点。这就是我感到困惑的地方。即使在 oracle 文档中,它也没有解释如何实例化它,而且我不确定它是否与它的超类一起被调用,或者我是否必须专门调用它。
  • 我认为每个人都会遇到这种情况,如果您一直在编写代码,就很难看到它,欢迎您
【解决方案2】:

在 main 方法中,您只需实例化一个 DVD 对象,而不是 ExtendedDVD 对象。

替换

DVD dvd= new DVD(dvdName,itemNum,quantity,price);

类似

DVD dvd= new ExtendedDVD(year);

很明显,您可能需要ExtendedDVD 中的另一个构造函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2014-08-12
    • 2016-04-04
    • 2012-11-09
    • 1970-01-01
    相关资源
    最近更新 更多