一尘不染

创建对象时,“无法从静态上下文引用的非静态变量”

java

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

阅读 242

收藏
2020-09-08

共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中,有两种类型的嵌套类:“静态嵌套类”和“内部类”。没有static关键字,它是一个内部类,您将需要一个实例ShowBike来访问ShowBike.Bicycle

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

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

2020-09-08