我有一个包含不同类型门票的程序。我有Ticket
,AdvanceTicket
和StudentAdvanceTicket
。我打印机票的价格为50美元,预售票价为30美元和40美元),学生预售票的价格分别为15美元和20美元。
条件为if daysAhead >= 10
的两个选项。
我花了好几个小时试图解决这个问题,我需要帮助。
Ticket.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)
答案 0 :(得分:3)
当您致电getPrice()
StudentAdvanceTicket
时,您的计划实际上会调用AdvanceTicket
的实施,这将返回30美元或40美元。
现在当您为toString()
致电StudentAdvanceTicket
时,它会从toString
拨打super
,AdvanceTicket
就是getPrice()
对象的price
方法,再次只返回30美元或40美元,并且不会使用getPrice
成员变量。
正确的解决方案是覆盖StudentAdvanceTicket
类的super.getPrice()
。在该方法中,您调用.btn_primary_cancel {
a#{&} {
line-height: 4rem;
}
}
,然后使用该操作进行价格操作。
答案 1 :(得分:1)
在StudentAdvanceTicket
中存在编译错误,因为super.price
无法解析。