如何返回私有变量

时间:2014-10-05 17:59:27

标签: java

好的,所以我试图更好地理解如何从我创建的类中返回一个私有变量。我只提供了我的主要程序的一小段来解释我的问题,所以如果需要更多信息,请告诉我。我的目标是从类中返回一个字符串(工作得很好),但也可以根据需要单独返回私有变量(下面使用的示例是“flight_number”)。

public class Flights {
    private String dest_city, dest_state, departureDate, departureTime;
    private int flight_number;

    public Flights(String city, String state, String dDate, String dTime, int flightNumber) {
        dest_city = city;
        dest_state = state;
        departureDate = dDate;  
        departureTime = dTime;
        flight_number = flightNumber;
    }

    public String toString() {
        return "Flight number: " + flight_number + " Destination: " + dest_city + "," + dest_state + "  Departing  on:" + departureDate + " at" + departureTime + ".";
    }
}

public class dummy {
    public static void main(String[] args) {
        // Uses the constructor to set values
        Flights flight1 = new Flights("Houston", "Texas", "12/20/2014", "12:40 pm", 100);
        System.out.println(flight1);
        System.out.println(flight_number); // Error: `flight_number` cannot be resolved to a variable.
    }
}

2 个答案:

答案 0 :(得分:4)

您需要在public中添加Flights getter ,然后从main调用它:

public class Flights {
    // all the private fields
    public int getFlightNumber() {
        return this.flight_number;
    }
}

Main

public static void main(String[] args) {
    Flights flight1 = new Flights("Houston", "Texas"); //...
    System.out.println(flight1);
    System.out.println(flight1.getFlightNumber());  // call the getter
}

答案 1 :(得分:0)

你应该从像eclipse这样的编辑器开始,这应该可以帮助你快速入门。 Getters和Setters是你需要的,但是从Eclipse开始,你应该做得更好。