-1

I am just beginning Java programming and I was following this example and I keep getting this "non-static variable this cannot be referenced from a static content" error. This code is supposed to print out the cadence, speed, and gear. I get the error at the Bicycle bike1=new Bicycle(); and Bicycle bike2=new Bicycle(); Here is the code:

public class BicycleDemo 
{

/**
 * @param args the command line arguments
 */
public static void main(String[] args) 
{
    // TODO code application logic here
    Bicycle bike1= new Bicycle();
    Bicycle bike2= new Bicycle();

    bike1.changeCadence(50);
    bike1.speedUp(10);
    bike1.changeGear(2);
    bike1.printStatments();

    bike2.changeCadence(40);
    bike2.speedUp(12);
    bike2.applyBreaks(3);
    bike2.printStatments();
}

class Bicycle
{
   int cadence=0;
   int speed=0;
   int gear=1;

   void changeCadence(int value)
   {
       cadence=value;
   }
   void changeGear(int value)
   {
       gear=value;
   }
   void speedUp(int increment)
   {
       speed=speed+increment;
   }
   void applyBreaks(int decrement)
   {
       speed=speed-decrement;
   }
   void printStatments()
   {
       System.out.println("Cadence:"+cadence+"Speed:"+speed+"Gear:"+gear);
   }
}

3 Answers3

1

The problem is that Bicycle class is an inner class and cannot be directly instantiated in a static method. Just move it outside BicycleDemo class:

public class BicycleDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)  {
        // TODO code application logic here
        Bicycle bike1= new Bicycle();
        Bicycle bike2= new Bicycle();

        bike1.changeCadence(50);
        bike1.speedUp(10);
        bike1.changeGear(2);
        bike1.printStatments();

        bike2.changeCadence(40);
        bike2.speedUp(12);
        bike2.applyBreaks(3);
        bike2.printStatments();
    }
}

//note the braces ( } ) up here

class Bicycle {
    //definition here...
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

Either change class Bicycle to static class Bicycle or, preferably, move it into a separate file (Bicycle.java).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

You can't access non-static inner classes without having a referrence to the object of outer class. In you case, you can't just instantiate Bicycle bike1= new Bicycle();

You work in static context (public static void main(String[] args)), so you have to create an instance of outer class (BicycleDemo) first, and then create instances of inner class. In this case you need to write:

BicycleDemo demo = new BicycleDemo ();

Bicycle bike1= demo.new Bicycle();
Bicycle bike2= demo.new Bicycle();

...