gpt4 book ai didi

java - 创建对象时"Non-static variable this cannot be referenced from a static context"

转载 作者:太空宇宙 更新时间:2023-11-04 11:07:05 24 4
gpt4 key购买 nike

我编写了下面的代码来测试 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 静态。

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中有two types of nested classes :“静态嵌套类”和 "Inner class" 。如果没有 static 关键字,它是一个内部类,您将需要 ShowBike 的实例来访问 ShowBike.Bicycle:

ShowBike showBike = new ShowBike();
Bicycle bike = showBike.new Bicycle(5);
<小时/>

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

关于java - 创建对象时"Non-static variable this cannot be referenced from a static context",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46385932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com