为什么我的构造函数中有一个非静态变量错误?

vmjh9lq9  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(292)

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

java中的内部类-非静态变量错误(4个答案)
java内部类和静态嵌套类(26个答案)
4个月前关门了。
我很难编译我的代码。我盯着这个代码看了好几个小时,不知道出了什么问题。
这是我的密码:密码

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());
    }
}

这就是我一直得到的错误:错误

test.java:36: error: non-static variable this cannot be referenced from a static context
    University tsu = new University();
                     ^

提前感谢您的帮助!

xlpyo6sf

xlpyo6sf1#

您的代码定义 University 作为非静态类(有关更详细的解释,请参见嵌套类)。你应该声明 University 具体如下:

static class University {
    // ...
}

相关问题