所以我正在制作一个使用继承和多态性销售三张票的售票亭。输出需要如下所示。
常规赛:
Ticket type: Walkup, Number: 123, Price: 10.00
Ticket type: Advance, Number: 234, Price: 7.50
Ticket type: Student Advance, Number: 345, Price: 3.75 (ID Required)
final :
Ticket type: Walkup, Number: 321, Price: 12.00
Ticket type: Advance, Number: 432, Price: 9.00
Ticket type: Student Advance, Number: 543, Price: 4.50 (ID Required)
我的输出是这样的。
常规赛:
Ticket type: Walkup, Number: 123, Price: 10.00
Ticket type: Advance, Number: 234, Price: 10.00
Ticket type: Student Advance, Number: 345, Price: 10.00
final :
Ticket type: Walkup, Number: 321, Price: 12.00
Ticket type: Advance, Number: 432, Price: 12.00
Ticket type: Student Advance, Number: 543, Price: 12.00
所以我的问题是如何在我的代码中更改静态 double 价格以使其成为这些价格而不将整个价格更改为我设置的价格。
这是我的代码:
public abstract class Ticket {
protected String ticketNumber;
protected static double price = 10.00;
protected String ticketName;
// constructor so i can change my ticket number in the main as a parameter
public Ticket(String string) {
this.ticketNumber = string;
}
// get name in other classes
public String getName() {
return ticketName;
}
// get price
public double getPrice() {
return price;
}
// so i can chang the price in the main
public static void setPrice(double price) {
Ticket.price = price;
}
// toString method so i can print my descriptive information.
public String toString() {
String result = String.format("\tTicket type: %s, Number: %s, Price: %.2f", getName(), ticketNumber, getPrice());
return result;
}
}
public class WalkUpTicket extends Ticket {
public WalkUpTicket(String string) {
super(string);
}
public String getName() {
return this.ticketName = "Walkup";
}
}
public class AdvanceTicket extends Ticket {
public AdvanceTicket(String string) {
super(string);
}
public String getName() {
return "Advance";
}
}
public class StudentAdvanceTicket extends AdvanceTicket {
public StudentAdvanceTicket(String string) {
super(string);
}
public String getName() {
return "Student Advance";
}
}
最佳答案
静态实例变量在同一类的每个实例之间共享。它们是类绑定(bind)的,而不是实例绑定(bind)的。
如前所述,您需要从 Ticket
类中删除静态价格,并将其放入每个扩展它的类中。由于变量是类绑定(bind)的,因此每个子类都需要一个。您还必须在每个子类中创建一个setPrice()
方法来修改每个类型的价格。
关于java - 在其他类中更改 static double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029064/