如何访问在Bus类构造方法中创建的Trip对象?
问题描述
我在Bus类的构造方法里创建了Trip对象,但没法在Main类里访问它。一开始以为这个对象存在Trip类里,控制台提示找不到符号;后来又以为在Bus类里,还是访问不了。
Main类代码
public class Interface { public static void main(String args[]) { Bus bus1 = new Bus(1); Trip.trip1.toString(); } }
Bus类代码
public class Bus { private int tripNumber; private String model; private String type; private int age; private int capacity; private int remainingCapacity; private boolean[][] seats; public Bus(int tripNumber) { this.tripNumber = tripNumber; if (tripNumber==1) { this.model = "Setra"; this.type = "2+2"; this.age = 8; this.capacity = 40; this.remainingCapacity = 23; Trip trip1 = new Trip(this, tripNumber); } } public String toString() { return ("\n\tBus Information:\n\t\tBus: " + this.model + "\n\t\tType: " + this.type + "\n\t\tAge: " + this.age + "\n\t\tCapacity" + this.capacity + "\n\t\tRemainingCapacity" + this.remainingCapacity); } }
Trip类代码
public class Trip { private int tripNumber; private String date; private String origin; private String destination; private String departureTime; private String arrivalTime; private Bus assignedBus; public Trip(Bus bus, int tripNumber) { if (tripNumber==1) { this.tripNumber = 1; this.assignedBus = bus; this.date = "27/11/2022"; this.origin = "Ankara"; this.destination = "Istanbul"; this.departureTime = "00:15"; this.arrivalTime = "06:30"; } } public String toString() { return tripNumber + ") Trip Information: \n\tDate: " + this.date + "\n\tFrom: " + this.origin + " to " + this.destination + "\n\tTrip time: " + this.departureTime + " to " + this.arrivalTime + this.assignedBus.toString(); } }
解决方案
问题根源
- 你在Bus构造方法里创建的
Trip trip1是局部变量,仅在构造方法的if代码块范围内有效,Bus类外部甚至类内其他方法都无法访问。 - 你尝试用
Trip.trip1访问,这是错误地将trip1当成了Trip类的静态成员变量,但Trip类中并未定义这个静态变量,因此编译器报“找不到符号”错误。
修复步骤
给Bus类添加Trip类型的成员变量
在Bus类的私有成员声明区添加一行:private Trip assignedTrip;修改Bus构造方法的对象赋值逻辑
将构造方法内的局部变量创建代码,改为给成员变量赋值:// 替换原来的Trip trip1 = new Trip(this, tripNumber); this.assignedTrip = new Trip(this, tripNumber);给Bus类添加getter方法
提供外部访问Bus类中Trip对象的入口:public Trip getAssignedTrip() { return assignedTrip; }修改Main类的调用逻辑
通过Bus实例获取Trip对象,再调用toString方法:public class Interface { public static void main(String args[]) { Bus bus1 = new Bus(1); // 如果需要打印信息,加上System.out.println System.out.println(bus1.getAssignedTrip().toString()); } }
额外提示
- 若tripNumber不等于1,
assignedTrip会是null,调用toString前建议添加非空判断,避免空指针异常。 - 从业务逻辑看,Bus与Trip是关联关系,将Trip实例存储在Bus类中是更合理的设计。
内容的提问来源于stack exchange,提问作者Arson1st
相关产品推荐
相关产品推荐

