无法引用非静态变量

时间:2018-04-09 21:13:04

标签: java main non-static

我试图通过在多个函数中划分代码来使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();
    }

但我得到的错误是这样的:

  

错误:非静态变量,无法从静态上下文引用         RentalAgency agency = this.createAgency();

我真的不知道如何纠正,我查了一下,当你尝试在没有启动的东西上使用某个方法时,它似乎会发生?

3 个答案:

答案 0 :(得分:3)

将方法签名更改为以下内容:

public static RentalAgency createAgency() {...}

您还需要从this方法移除main()引用,只需按以下方式调用该方法:

RentalAgency agency = createAgency();

答案 1 :(得分:1)

java中的

this指的是您手头的对象。现在,在您的情况下,没有对象只是在主方法中引用RentalAgency。

要使用this,您需要创建一个对象。但是,我猜你正在使用createAgency方法而不是通常的构造方法。因此,请将createAgency标记为static并在不使用this方法的main的情况下调用它。

public static RentalAgency createAgency(){
   //Some code goes here
}

public static void main(String[] args) throws UnknownVehicleException 
{
  RentalAgency agency = createAgency();
}

答案 2 :(得分:0)

main()是一个静态函数,因此没有从内部引用的实例this。尝试制作createAgency()静态:

public static RentalAgency createAgency() {
    ...
}