所以我正在建立一个使用继承和多态来销售三张票的售票亭。输出需要看起来像这样。
常规季节:
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)
决赛:
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
决赛:
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
所以我的问题是如何更改我的代码中的静态双倍价格,使其成为那些价格而不会将整个价格更改为我设置的价格。
继承我的代码:
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";
}
}
答案 0 :(得分:1)
静态实例变量在同一个类的每个实例之间共享。它们类绑定,而不是实例绑定。
如上所述,您需要从Ticket
类中删除静态价格,而是将其放在扩展它的每个类中。由于变量是类绑定的,因此每个子类都需要一个。您还必须在每个子类中创建setPrice()
方法,以修改每种类型的价格。
答案 1 :(得分:0)
此设计模式的最佳折衷方案如下所示Inherit a Static Variable in Java ..如何从静态成员继承静态成员,从顶部答案:
abstract class Parent {
public abstract String getACONSTANT();
}
class Child extends Parent {
public static final String ACONSTANT = "some value";
public String getACONSTANT() { return ACONSTANT; }
}