gpt4 book ai didi

具有继承性的 Java Ticket 程序

转载 作者:行者123 更新时间:2023-11-29 08:37:22 25 4
gpt4 key购买 nike

我有一个包含不同类型门票的节目。我有 TicketAdvanceTicket 和一张 StudentAdvanceTicket。我打印的票价是 50 美元,预售票的价格是 30 美元和 40 美元),学生预售票的价格是 15 美元和 20 美元。

条件为 if daysAhead >= 10 的两个选项。

我花了几个小时试图解决这个问题,我需要帮助。

票证.java

public class Ticket {
private int number;

public Ticket(int number) {
this.number = number;
}

public double getPrice() {
return 50.0;
}

public String toString() {
return "Ticket #" + this.number + ", Price: $" + this.getPrice();
}
}

TicketMain.java

public class TicketMain {
public static void main(String[] args) {
Ticket[] tickets = new Ticket[5];
tickets[0] = new WalkupTicket(1);
tickets[1] = new AdvanceTicket(2,12);
tickets[2] = new AdvanceTicket(3,8);
tickets[3] = new StudentAdvanceTicket(4,17);
tickets[4] = new StudentAdvanceTicket(5,7);

for (int i = 0; i<5; i++) {
System.out.println(tickets[i]);
//System.out.println(" ");
}
}
}

AdvanceTicket.java

public class AdvanceTicket extends Ticket {
private int daysAhead;

public AdvanceTicket(int number, int daysAhead) {
super(number);
this.daysAhead = daysAhead;
}

public double getPrice() {
if (daysAhead >= 10) {
return 30.00;
} else {
return 40.00;
}
}

public String toString() {
if (daysAhead >= 10) {
return super.toString() + " (" + this.daysAhead + " days ahead, you got a great deal!)";
} else {
return super.toString() + " (" + this.daysAhead + " days ahead, you could have saved a bit more)";
}
}
}

最后的问题是...StudentAdvanceTicket.java

public class StudentAdvanceTicket extends AdvanceTicket {

public StudentAdvanceTicket(int number, int daysAhead) {
super(number, daysAhead);
super.price = super.getPrice() / 2;
}

public String toString() {
return super.toString() + " (ID Required) ";
}
}

这是我想要的输出。

Ticket #1, Price: $50.0
Ticket #2, Price: $30.0 (12 days ahead, you got a great deal!)
Ticket #3, Price: $40.0 (8 days ahead, you could have saved a bit more)
Ticket #4, Price: $15.0 (ID Required)
Ticket #5, Price: $20.0 (ID Required)

最佳答案

当您为 StudentAdvanceTicket 调用 getPrice() 时,您的程序实际上是从 AdvanceTicket 调用实现,它将返回 $30 或 $40。

现在,当您为 StudentAdvanceTicket 调用 toString() 时,它会从 super 调用 toString,它是用于 AdvanceTicket 的那个,那个调用对象的 getPrice() 方法,同样,它只返回 $30 或 $40 并且不使用 >price 成员变量。

正确的解决方案是覆盖 StudentAdvanceTicket 类的 getPrice。在该方法中,您调用 super.getPrice(),然后用它进行价格操作。

关于具有继承性的 Java Ticket 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915954/

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