34

I wrote the below code to test the concept of classes and objects in Java.

public class ShowBike {
    private class Bicycle {
        public int gear = 0;
        public Bicycle(int v) {
            gear = v;
        }
    }

    public static void main() {
        Bicycle bike = new Bicycle(5);
        System.out.println(bike.gear);
    }
}

Why does this give me the below error in the compiling process?

ShowBike.java:12: non-static variable this cannot be referenced from a static context
        Bicycle bike = new Bicycle(5);
                       ^
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
mko
  • 21,334
  • 49
  • 130
  • 191

5 Answers5

52

Make ShowBike.Bicycle static.

public class ShowBike {

    private static class Bicycle {
        public int gear = 0;
        public Bicycle(int v) {
            gear = v;
        }

    }

    public static void main() {
        Bicycle bike = new Bicycle(5);
        System.out.println(bike.gear);
    }
}

In Java there are two types of nested classes: "Static nested class" and "Inner class". Without the static keyword it is an inner class and you will need an instance of ShowBike to access ShowBike.Bicycle:

ShowBike showBike = new ShowBike();
Bicycle bike = showBike.new Bicycle(5);

Static nested classes and normal (non-nested) classes are almost the same in functionality, it's just different ways to group things. However, when using static nested classes, you cannot put definitions of them in separated files, which will lead to a single file containing a lot of class definitions.

Andy
  • 1,663
  • 10
  • 17
Alvin Wong
  • 12,210
  • 5
  • 51
  • 77
7

Bicycle is an inner class, so you need outer class instance to create inner class instance like :

ShowBike sBike = new ShowBike();
Bicycle bike = sBike.new Bicycle(5);

Or you can simply declare Bicycle class as static to make your current way work.

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
3

The main method cannot access a non-static member of its class.

By the way, classes should be named after nouns, not verbs. So a better way to do it is :

private class Bicycle {
    public int gear = 0;

    public Bicycle(int v) {
        gear = v;
    }

    public void showGear() {
        System.out.println(gear);
    }

    public static void main(String[] args) {
        Bicycle bike = new Bicycle(6);
        bike.showGear(); // Notice that the method is named after a verb
    }
}
ktm5124
  • 11,861
  • 21
  • 74
  • 119
2

You need to create outer class object instate of inner class. or you need to make inner class as static. so for inner class no object required.

Janny
  • 681
  • 1
  • 8
  • 33
1

Your Bicycle class is not static, and therefore cannot be used in a non-static method. If you want to use it in the main method, change it to

private static class Bicycle
crazylpfan
  • 1,038
  • 7
  • 9