首页 > 解决方案 > 如何解决从子类为其父类调用方法?

问题描述

如果我将 Detective 添加为 Book,我该如何调用该setPrice方法(因为您不能为父类调用子方法)?

这是代码:

public class Book {
  String title;
//Contructors, get/setters, Override output methods
}
public class Detective extends Book {
  int price;
  //Contructors, get/setters, Override output methods
}
public class BookManager {
  Book[] list;
  int count = 0;
  final int MAX = 100;
  //Contructors, get/setters, Override output methods

  public void add(Book x) {
        if(count >= MAX) {
            System.out.println("Failed!");
        }
        list[count] = x;
        count++;
        System.out.println("Added!");
    }

  public void updatePrice(String title, int newPrice) {
     for(int i = 0; i < count; i++) {
        if(list[i].equals(title) && list[i] instanceof Detective) {
          //list[i].setPrice(newPrice) is wrong//
        } 
     }
  }
}
public static void main(String[] args) {
  BookManager list = new BookManager();
  Detective de = new Detective("abc", 123);
  list.add(de);
  //list.updatePrice("abc", 456); is wrong//
}

还有其他方法可以更新价格吗?

标签: java

解决方案


一些选项,取决于数据应该如何建模。


1 - 只需使用强制转换Detective来使用其方法:

if (list[i].equals(title) && list[i] instanceof Detective) {
    Detective dectective = (Detective) list[i];
    detective.setPrice(newPrice);

2 - 每本书不应该有价格吗?

public class Book {
    String title;
    //Contructors, get/setters, Override output methods

    public void setPrice(int price) {
        ...
    }
}

现在调用它很简单:

// instanceof not need here for this to work
if (list[i].equals(title) && list[i] instanceof Detective) {
    list[i].setPrice(newPrice);

最终该方法为空Book但被覆盖Detective

public class Book {
    ...

    public void setPrice(int price) {
        // intentionally empty, overridden in aubclasses
    }
}

public class Detective extends Book {
    ...
    @Override
    public void setPrice(int p) {
        ...
    }
}

3 - 更进一步,假设没有 just-a-Book,即只有子类Book: 制作类和方法abstract

public abstract class Book {  // maybe make  this an interface
    ...
    public abstract void setPrince(int p);
}

并且每个子类都必须实现该方法

public class Detective extends Book {
    ...
    @Override
    public void setPrice(int p) [
        ...
    }
}

并调用

if (list[i].equals(title) && list[i] instanceof Detective) {
    list[i].setPrice(newPrice);

这不允许在中创建书籍new Book(...);要创建一本书,只允许子类,例如Book book = new Detective(...)


推荐阅读