
本文详细探讨了在java中,当一个类(如`bus`)的构造器内创建另一个对象(如`trip`)时,如何在外部类(如`interface`的`main`方法)中正确访问该对象。核心问题在于变量作用域的理解和实例成员的正确引用。教程将通过实例代码演示如何将局部变量提升为类成员变量,并利用getter方法实现封装和安全访问,同时提供处理多对象场景的设计建议,以提升代码的可维护性和扩展性。
在Java中,变量的作用域决定了其可访问的范围。当我们在一个方法的内部(包括构造器)声明一个变量时,该变量被称为局部变量。局部变量只在该方法或代码块内部有效,一旦方法执行完毕,局部变量就会被销毁,无法从外部访问。
原始代码中的Bus类存在的问题就在于此:
public class Bus
{
// ... 其他成员变量
// private Trip trip1; // 缺少这一行,导致 trip1 成为局部变量
public Bus(int tripNumber)
{
this.tripNumber = tripNumber;
if (tripNumber==1)
{
// 在构造器内部声明的 trip1 是局部变量
Trip trip1 = new Trip(this, tripNumber);
}
}
// ...
}在上述代码中,Trip trip1 = new Trip(this, tripNumber); 语句将trip1声明为Bus构造器内部的一个局部变量。这意味着trip1只在Bus构造器的if (tripNumber==1)代码块中存在。一旦构造器执行完毕,trip1就超出了作用域,无法再被Bus类的其他方法或外部类访问。
修正方法:将局部变量提升为实例变量
立即学习“Java免费学习笔记(深入)”;
要使Trip对象能够在Bus类的生命周期内持续存在并被外部访问,我们需要将其声明为Bus类的实例变量(或称成员变量)。实例变量属于类的每一个对象,并在对象创建时被初始化,直到对象被垃圾回收。
public class Bus
{
// ... 其他成员变量
private Trip trip; // 将 trip 声明为实例变量
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 赋值
this.trip = new Trip(this, tripNumber);
}
}
// ...
}通过将Trip trip;声明在类级别,trip现在是Bus对象的一个属性。当Bus对象被创建时,trip变量也随之存在,并可以在Bus对象的生命周期内被访问。
解决了Bus类内部Trip对象的可见性问题后,下一步是解决如何在Interface(主类)中正确访问它。原始的Interface类试图通过Trip.trip1.toString();来访问trip1,这存在两个问题:
引入 Getter 方法:封装与访问控制
在面向对象编程中,为了实现封装性,我们通常将实例变量声明为private,并通过公共的getter方法来提供对这些变量的受控访问。这不仅保护了对象的内部状态,还提供了未来修改内部实现的灵活性,而无需更改外部调用代码。
首先,在Bus类中添加一个getTrip()方法:
public class Bus
{
// ... 其他成员变量
private Trip trip; // 实例变量
public Bus(int tripNumber)
{
// ... 构造器逻辑
if (tripNumber==1)
{
// ... 赋值其他属性
this.trip = new Trip(this, tripNumber);
}
}
// 为 trip 实例变量提供公共的 getter 方法
public Trip getTrip() {
return this.trip;
}
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);
}
}然后,在Interface类中,通过Bus对象的实例来调用getTrip()方法,获取Trip对象,再对其进行操作:
public class Interface
{
public static void main(String args[])
{
Bus bus1 = new Bus(1);
// 通过 bus1 实例的 getTrip() 方法获取 Trip 对象
if (bus1.getTrip() != null) { // 检查是否成功创建了 Trip 对象
System.out.println(bus1.getTrip().toString());
} else {
System.out.println("Trip object not created for bus1.");
}
}
}通过这种方式,我们不仅正确地访问了Trip对象,还遵循了面向对象的封装原则。
以下是经过修正和优化的完整代码示例:
Bus.java
public class Bus
{
private int tripNumber;
private String model;
private String type;
private int age;
private int capacity;
private int remainingCapacity;
private boolean[][] seats;
private Trip trip; // 将 trip 声明为实例变量
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;
this.trip = new Trip(this, tripNumber); // 为实例变量 trip 赋值
}
// 如果 tripNumber 不是1,trip 将保持为 null,这是需要注意的。
// 可以考虑在构造器末尾添加一个默认的 trip 赋值或者抛出异常。
}
// 提供对 trip 实例的公共访问方法
public Trip getTrip() {
return this.trip;
}
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.java
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) // 这里的条件可能需要更灵活,或者从 Bus 构造器传递所有必要参数
{
this.tripNumber = tripNumber; // 应该使用传入的 tripNumber
this.assignedBus = bus;
this.date = "27/11/2022";
this.origin = "Ankara";
this.destination = "Istanbul";
this.departureTime = "00:15";
this.arrivalTime = "06:30";
}
// 同样,如果 tripNumber 不是1,Trip 对象可能不会被完全初始化
}
public String toString()
{
// 检查 assignedBus 是否为 null,以避免 NullPointerException
String busInfo = (this.assignedBus != null) ? this.assignedBus.toString() : "\n\t\tNo assigned bus information.";
return tripNumber + ") Trip Information: \n\tDate: " + this.date + "\n\tFrom: " + this.origin + " to " + this.destination + "\n\tTrip time: " + this.departureTime + " to " + this.arrivalTime + busInfo;
}
}Interface.java
public class Interface
{
public static void main(String args[])
{
Bus bus1 = new Bus(1); // 创建一个 tripNumber 为 1 的 Bus 对象
// 通过 Bus 实例的 getter 方法获取 Trip 对象
Trip tripForBus1 = bus1.getTrip();
if (tripForBus1 != null) {
System.out.println(tripForBus1.toString());
} else {
System.out.println("No trip assigned to bus1 for the given trip number.");
}
// 示例:如果创建的 Bus 没有对应的 Trip (例如 tripNumber 不是1)
Bus bus2 = new Bus(2);
Trip tripForBus2 = bus2.getTrip();
if (tripForBus2 != null) {
System.out.println(tripForBus2.toString());
} else {
System.out.println("No trip assigned to bus2 for the given trip number.");
}
}
}封装原则:始终将实例变量声明为private,并通过公共的getter(和setter,如果需要修改)方法来访问它们。这不仅保护了数据,还提高了代码的模块化和可维护性。
构造器的职责:构造器应主要负责初始化对象的状态。避免在构造器中执行复杂的业务逻辑,特别是那些可能失败或耗时的操作。如果对象创建逻辑复杂,可以考虑使用工厂模式。
处理多对象关联:当前设计中,一辆Bus只能关联一个Trip对象(通过private Trip trip;)。在实际应用中,一辆巴士可能执行多趟行程,或者需要管理历史行程。在这种情况下,应该使用集合类型(如List<Trip>或Map<Integer, Trip>)来存储多个Trip对象:
public class Bus {
private List<Trip> trips; // 一辆巴士可以有多趟行程
public Bus(int initialCapacity) {
this.trips = new ArrayList<>(); // 初始化行程列表
// ... 其他初始化
}
public void addTrip(Trip trip) {
this.trips.add(trip);
}
public List<Trip> getTrips() {
return Collections.unmodifiableList(this.trips); // 返回不可修改的列表,保护内部状态
}
// ...
}这样,在Bus构造器中可以创建并添加多个Trip对象,或者在后续通过addTrip方法动态添加。
条件初始化:在Bus和Trip的构造器中,都存在if (tripNumber == 1)这样的条件判断。这使得只有特定tripNumber的实例才会被完全初始化,而其他情况下的对象可能处于不完整或null的状态。这可能导致运行时出现NullPointerException。
Null 安全:在Interface类中调用bus1.getTrip()后,务必检查返回的Trip对象是否为null,以避免潜在的NullPointerException。同样,在Trip的toString()方法中,也应检查assignedBus是否为null。
正确访问在构造器中创建的对象是Java面向对象编程中的一个基本但重要的概念。通过理解变量作用域(局部变量与实例变量的区别)、将相关对象声明为实例变量,并遵循封装原则使用getter方法,我们可以构建出结构清晰、可维护性高且健壮的Java应用程序。此外,对于复杂的对象关联,应考虑使用集合类型来管理,并时刻注意代码的健壮性和Null安全。
以上就是Java中构造器内创建对象的正确访问与管理实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号