ava图书馆通过多态实现计算罚金代码,分为儿童书籍,成人书籍,音像制品,读者可一次借阅多本书籍和音像制品代码
时间: 2023-05-19 20:01:20 浏览: 273
Java书籍借阅管理系统
5星 · 资源好评率100%
非常感谢您的提问。以下是 Java 图书馆通过多态实现计算罚金的代码:
```
public abstract class Item {
protected String title;
protected int playingTime;
protected boolean gotIt;
protected int daysOverdue;
public Item(String title, int playingTime) {
this.title = title;
this.playingTime = playingTime;
this.gotIt = false;
this.daysOverdue = 0;
}
public void setGotIt(boolean gotIt) {
this.gotIt = gotIt;
}
public void setDaysOverdue(int daysOverdue) {
this.daysOverdue = daysOverdue;
}
public abstract double calculateFine();
public String toString() {
String result = title + " (" + playingTime + " mins)";
if (gotIt) {
result += "*";
}
return result;
}
}
public class Book extends Item {
private String author;
public Book(String title, String author, int playingTime) {
super(title, playingTime);
this.author = author;
}
public double calculateFine() {
double fine = 0.0;
if (daysOverdue > 0) {
fine = daysOverdue * 0.25;
}
return fine;
}
public String toString() {
return super.toString() + " by " + author;
}
}
public class Audio extends Item {
private String artist;
public Audio(String title, String artist, int playingTime) {
super(title, playingTime);
this.artist = artist;
}
public double calculateFine() {
double fine = 0.0;
if (daysOverdue > 0) {
fine = daysOverdue * 0.50;
}
return fine;
}
public String toString() {
return super.toString() + " by " + artist;
}
}
public class Library {
private ArrayList<Item> items;
public Library() {
items = new ArrayList<Item>();
}
public void addItem(Item item) {
items.add(item);
}
public void printCatalog() {
for (Item item : items) {
System.out.println(item);
}
}
public void calculateFine() {
for (Item item : items) {
double fine = item.calculateFine();
if (fine > 0.0) {
System.out.println(item + " fine: $" + fine);
}
}
}
}
```
读者可以一次借阅多本书籍和音像制品,可以在 Library 类中添加一个 ArrayList<Loan> loans,Loan 类中包含 Item 和借阅日期等信息。calculateFine() 方法中需要遍历 loans,计算每个 Loan 的罚金。
阅读全文