好吧,我想更好地了解如何从我创建的类中返回一个私有变量。我只提供了一个我的主程序的小片段来解释我的问题,所以如果需要更多信息,请告诉我。我的目标是从类中返回一个字符串(很好用),但也可以根据需要单独返回私有变量(下面使用的示例是“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.
}
}
我的猜测是,你还没有提前编写java代码。继续学习,并保持与给定示例代码更接近。然后尝试使用工作示例。慢慢走。 – Matthias 2014-10-05 18:02:10
'私人'意味着...私人。根据“private”的定义,虚拟类可能无法访问另一个班级Flights的私人字段。 http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – 2014-10-05 18:02:19
请在发布之前先格式化您的代码。您可以预览您的问题将如何查找原因。 – Pshemo 2014-10-05 18:02:30