java - 在其他类中更改 static double

标签 java inheritance static

所以我正在制作一个使用继承和多态性销售三张票的售票亭。输出需要如下所示。

常规赛:

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/

相关文章:

java - 对象内部的静态对象引用被复制吗?

c - 我想在代码中使用delete()函数删除节点,但之后我在display()函数中进入无限循环?

java - 重新部署 JBoss AS war 后最终静态值未更新

java - Python 和 Java 中 import 语句的含义有什么区别?

java - 如何确定并保存远程用户的 MAC 地址?

Python:从 ttk.Frame 继承时不能使用关键字参数

java - 如何覆盖具有默认(包)可见性范围的方法?

java - Spring MVC中init binder的目的是什么

java - 使用或覆盖已弃用的 API

ruby - 如何编写适用于所有数字的方法