gpt4 book ai didi

java - 如何解决从子类为其父类调用方法的问题?

转载 作者:行者123 更新时间:2023-12-02 09:27:19 25 4
gpt4 key购买 nike

如果我将侦探添加为书,我如何调用 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(...)

关于java - 如何解决从子类为其父类调用方法的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58256054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com