我编写了以下代码来测试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); ^
使ShowBike.Bicycle静态。
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:
static
ShowBike
ShowBike showBike = new ShowBike(); Bicycle bike = showBike.new Bicycle(5);
静态嵌套类和普通(非嵌套)类的功能几乎相同,只是对事物进行分组的方式不同。但是,在使用静态嵌套类时,不能将它们的定义放在单独的文件中,这将导致单个文件包含很多类定义。