“Non-static variable this cannot be referenced from a static context” when creating an object

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.

Leave a Comment