繁体   English   中英

如何到达从另一个类的构造函数创建的 object

[英]How do I reach an object that created from another class's constructor

我试图在总线 class 构造函数中创建行程 object,但我无法从主 class 到达它。

我以为我在 Trip class 中存储了 trip object 但控制台说找不到符号,然后我认为它存储在 Bus class 但它也没有用

主 class

public class Interface
{
    public static void main(String args[])
    {       
        Bus bus1 = new Bus(1);
        Trip.trip1.toString();
    }
}
    

公交 class

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);
    }
}

行程 class

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();
    }
}

代码中有几个问题。

总线.java

您已将trip1变量声明为仅存在于构造函数中的局部变量,因此它不可用且无法在其他地方引用。 将其设为 class 变量,使其可供 class 的实例使用。

接口.java

您正在尝试访问 class 级别的trip1变量,而您应该在总线class 的实例上访问它(类似于bus1.trip1.toString()最好为此目的创建一个 getter)。 注意:您需要解决第一个问题才能正常工作。

请在此处查看工作代码 - https://ideone.com/ej8IGD (请注意,主要 class 名称已根据平台要求更改)

虽然这行得通——但我强烈建议您稍微重组代码以处理诸如处理不止一次旅行之类的情况(提示:使用列表/数组)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM