问题描述
我编写了以下代码来测试Java中类和对象的概念。
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);
^
推荐答案
制作 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);
}
}
在Java中有:静态嵌套类和。没有 static
关键字,它是一个内部类,你需要一个 ShowBike
的实例来访问 ShowBike.Bicycle
:
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.
这篇关于“非静态变量,这不能从静态上下文引用”。在创建对象时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!