如果我将侦探添加为书籍,该如何调用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//
}
还有其他更新价格的方法吗?
答案 0 :(得分:1)
某些选项,取决于数据的建模方式。
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-进一步,假设没有一本书,即仅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(...)
答案 1 :(得分:0)
我通常要做的是定义一个由父母实现且孩子可以调用的接口。
接口:
public interface IBookListener {
void updatePrice (String title, int newPrice);
}
在父级:
public class BookManager implements IBookListener {
public void add(Book x) {
x.setListener(this);
...
}
...
public void updatePrice (String title, int newPrice) {
...
}
}
在孩子中:
public class Book {
...
private IBookListener listener;
public setLister(IBookListener listener) {
this.listener = listener;
}
public someMethod () {
listener.updatePrice("title", 1);
}
}