创建对象时的“不能从静态上下文中引用此非静态变量”

2022-09-01 09:31:59

我编写了下面的代码来测试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);
    }
}

为什么这会在编译过程中给我带来以下错误?

ShowBike.java:12: non-static variable this cannot be referenced from a static context
        Bicycle bike = new Bicycle(5);
                       ^

答案 1

设为静态。ShowBike.Bicycle

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);
    }
}

在Java中,有两种类型的嵌套类:“静态嵌套类”和“内部类”。如果没有关键字,它是一个内部类,您将需要一个实例来访问:staticShowBikeShowBike.Bicycle

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

静态嵌套类和普通(非嵌套)类在功能上几乎相同,只是分组方式不同。但是,在使用静态嵌套类时,不能将它们的定义放在单独的文件中,这将导致单个文件包含大量类定义。


答案 2

Bike 是一个内部类,因此您需要外部类实例来创建内部类实例,例如:

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

或者,您可以简单地将类声明为使当前方式正常工作。Bicyclestatic