gpt4 book ai didi

java - 为什么我的构造函数出现非静态变量错误?

转载 作者:行者123 更新时间:2023-12-02 10:47:20 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Inner classes in Java - Non static variable error

(4 个回答)



Java inner class and static nested class

(28 个回答)


1年前关闭。




我无法编译我的代码。我盯着这段代码看了好几个小时,我不知道出了什么问题。
这是我的代码:
code

public class test{

class University {
private String name;
private int enrollment;
private boolean urban;

public University() {
name = "TSU";
enrollment = 8000;
urban = true;
}

public University(String name, int enrollment, boolean urban) {
this.name = name;
this.enrollment = enrollment;
this.urban = urban;
}

public int getEnrollment() {
return enrollment;
}

public void setEnrollment(int n) {
if (n > 0) {
n = n;
} else {
n = 0;
}
}
}

public static void main(String[] args) {
University tsu = new University();
University vu = new University("Vandy", 5800, true);
University mt = new University("MTSU", 7000, false);

tsu.setEnrollment(8500);
vu.setEnrollment(60000);

System.out.println(tsu.name + "\'s enrollment is " + tsu.getEnrollment());
}
}
这是我不断收到的错误:
error
test.java:36: error: non-static variable this cannot be referenced from a static context
University tsu = new University();
^
预先感谢您的帮助!

最佳答案

您的代码定义了 University作为一个非静态类(参见 Nested Classes 以获得更详细的解释)。您应该改为声明 University如下:

static class University {
// ...
}

关于java - 为什么我的构造函数出现非静态变量错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63772196/

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