我试图通过在多个函数中划分代码来使我的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();
}
但是我收到这样的错误:
我错误:非静态变量 这不能从静态上下文引用 租赁代理代理 = this.createAgency((;
真的不知道如何纠正,我查了一下,当您尝试对未启动的东西使用方法时,它似乎会发生?
将方法签名更改为以下内容:
public static RentalAgency createAgency() {...}
您还需要从 main()
方法中删除this
引用,并按以下方式调用该方法:
RentalAgency agency = createAgency();
中的this
是指您手头的对象。现在,在您的情况下,没有对象,只有主方法中租赁代理的引用。
要使用 this
,您需要创建一个对象。但是,我猜您正在使用createAgency
方法而不是通常的构造函数方法。因此,将createAgency
标记为static
并在不使用this
from 方法的情况下调用它main
。
public static RentalAgency createAgency(){
//Some code goes here
}
public static void main(String[] args) throws UnknownVehicleException
{
RentalAgency agency = createAgency();
}
(( 是一个静态函数,因此没有实例this
可以从内部引用。尝试将createAgency()
设为静态:
public static RentalAgency createAgency() {
...
}