Java票务程序编译错误求助:类定义与实例化问题
Java票务程序编译错误修复方案
先看修正后的完整可运行代码:
public class TicketTest { public static void main(String args[]) { int total_sales = 0; new WebTicket(10); new WebTicket(5); new CounterTicket(); new DiscountTicket(5, "Student"); new DiscountTicket(10, "Senior"); } } class Ticket { public static final int COUNTER_TICKET_PRICE = 50; public static final int WEB_TICKET_PRICE = 30; public static final int WEB_TICKET_LT_WEEK_PRICE = 40; public static final double DISCOUNT = 0.5; // 用静态变量实现全局共享的票序列号 public static int serial = 1; int price; int days; String type; // 父类构造方法,子类必须显式调用 public Ticket(int days, String type) { this.days = days; this.type = type; } } class WebTicket extends Ticket { public WebTicket(int days) { super(days, "Web"); // 票价计算逻辑放在构造方法内 if (days > 7) { price = WEB_TICKET_LT_WEEK_PRICE; } else { price = WEB_TICKET_PRICE; } System.out.println("Ticket: [serial= " + serial + " Price: " + price + "]"); serial += 1; } } class CounterTicket extends Ticket { public CounterTicket() { // 柜台票默认传入天数0和类型标识 super(0, "Counter"); price = COUNTER_TICKET_PRICE; System.out.println("Ticket: [serial= " + serial + " Price: " + price + "]"); serial += 1; } } class DiscountTicket extends Ticket { public DiscountTicket(int days, String type) { super(days, type); if (days > 7) { price = (int) (WEB_TICKET_LT_WEEK_PRICE * DISCOUNT); } else { price = (int) (WEB_TICKET_PRICE * DISCOUNT); } System.out.println("Ticket: [serial= " + serial + " Price: " + price + " Type: " + type + "]"); serial += 1; } }
错误原因及修复说明
1. Ticket类定义语法错误
你写的class Ticket(int days, String type)是Java Record的语法,但误用了class关键字而非record,导致编译报错“需要record”。另外Record无法被继承,而你需要子类扩展Ticket,因此必须改成普通类,手动添加构造方法和成员变量。
2. 子类代码放置位置错误
WebTicket、CounterTicket等子类中的if判断、System.out.println直接写在类体里,Java不允许在类的顶级作用域中放置执行语句(仅允许变量声明、静态代码块、构造方法、普通方法)。必须将这些业务逻辑移到构造方法中,这样实例化对象时才会执行。
3. 子类未显式调用父类构造方法
当父类定义了带参数的构造方法后,子类必须通过super(参数)显式调用父类构造来初始化父类成员,否则会触发编译错误。比如CounterTicket是无参实例化,所以要写无参构造方法,内部调用super(0, "Counter")传入默认值。
4. 序列号serial作用域错误
原代码中TicketTest和Ticket类各有一个serial,导致每个Ticket实例的序列号独立,无法实现全局递增。将serial改为Ticket类的静态变量,所有子类共享该变量,实例化时递增即可保证序列号连续。
5. 常量定义优化
给价格常量添加final修饰符,避免被意外修改,符合Java编码规范。
运行修正后的代码,控制台会输出如下票务信息:
Ticket: [serial= 1 Price: 40] Ticket: [serial= 2 Price: 30] Ticket: [serial= 3 Price: 50] Ticket: [serial= 4 Price: 15 Type: Student] Ticket: [serial= 5 Price: 20 Type: Senior]
内容的提问来源于stack exchange,提问作者Corrupted_RainbowGuy
相关产品推荐
相关产品推荐

