java - 如何解决从子类为其父类调用方法?
问题描述
如果我将 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//
}
还有其他方法可以更新价格吗?
解决方案
一些选项,取决于数据应该如何建模。
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(...)
推荐阅读
- ms-word - 自定义工具栏上的标准按钮不可见
- javascript - 链接 Promise 并在它们之间传递参数
- sql - 在 SELECT 语句中将名称拆分为多个部分
- android - Android 依赖库必须是完全相同的版本
- microsoft-graph-api - 通过 office-js 以编程方式获取回复/转发状态?
- git - 从主分支获取自身现有的提交不会产生合并冲突 Gerrit
- php - Laravel - 通知自定义
- typescript - 奇怪场景中的打字稿编译错误
- c# - C# 将值从 WebSocket 服务器线程发送到 Main()
- html - mat-select - mat-option 排序值