Search code examples
javaprogram-entry-pointnon-static

Non static variable cannot be referenced


I'm trying to make the code in my main() method as light as possible by dividing the code in multiple function, so for example I create an instance of a class RentalAgency with the following function :

/** 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;
  }

And in the main() I try to run this :

/**The main function to run the Agency and some renting
  */
    public static void main(String[] args) throws UnknownVehicleException {
      RentalAgency agency = this.createAgency();
    }

but I get an error like so :

error: non-static variable this cannot be referenced from a static context RentalAgency agency = this.createAgency();

Which I don't really know how to correct, I looked it up and it seems to occurs when you try to use a method on something that is not initiated ?


Solution

  • this in java refers to the object which you have in hand. Now, in your case there is no object just the reference of RentalAgency in main method.

    To use this, you need to create an object. But, I am guessing you are using createAgency method for that instead of the usual constructor approach. So, mark the createAgency as static and call it without using this from main method.

    public static RentalAgency createAgency(){
       //Some code goes here
    }
    
    public static void main(String[] args) throws UnknownVehicleException 
    {
      RentalAgency agency = createAgency();
    }