我试图通过将代码划分为多个函数来使 main() 方法中的代码尽可能精简,因此例如我使用以下函数创建 RentalAgency 类的实例:
/** Creates an Agency with some cars and motorbikes
*/
public RentalAgency createAgency(){
List<Vehicle> theVehicles = new ArrayList<Vehicle>();
Map<Client,Vehicle> rentedVehicles = new HashMap <Client,Vehicle>();
RentalAgency agency = new RentalAgency(theVehicles, rentedVehicles);
Vehicle v1 = new Vehicle("Renault","clio",1998,50);
agency.addVehicle(v1);
Vehicle v2 = new Vehicle("Renault","twingo",2000,40);
agency.addVehicle(v2);
Car c1 = new Car("Renault","scenic",2005, 80, 7);
agency.addVehicle(c1);
Car c2 = new Car("Citroen","c3",2006, 70, 5);
agency.addVehicle(c2);
MotorBike m1 = new MotorBike("Honda","CB",2015, 50, 500);
agency.addVehicle(m1);
MotorBike m2 = new MotorBike("Yamaha","MT",2017, 80, 750);
agency.addVehicle(m2);
return agency;
}
在 main() 中我尝试运行这个:
/**The main function to run the Agency and some renting
*/
public static void main(String[] args) throws UnknownVehicleException {
RentalAgency agency = this.createAgency();
}
但我收到这样的错误:
error: non-static variable this cannot be referenced from a static context RentalAgency agency = this.createAgency();
我真的不知道如何纠正,我查了一下,当您尝试对未启动的东西使用方法时,似乎会发生这种情况?
最佳答案
将方法签名更改为以下内容:
public static RentalAgency createAgency() {...}
您还需要从 main()
方法中删除 this
引用,并只需按以下方式调用该方法:
RentalAgency agency = createAgency();
关于java - 非静态变量不能被引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49741779/