1

I'm having trouble getting my code to compile. I've stared at this code for hours and I have no idea what is wrong.

Here's my code: 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());
    }
}

This is the error I keep getting: error

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

Thank you in advance for your help!

kingkupps
  • 3,284
  • 2
  • 16
  • 28
Chrys
  • 11
  • 3

1 Answers1

0

Your code defines University as a non-static class (see Nested Classes for a more detailed explanation). You should instead declare University as follows:

static class University {
    // ...
}
kingkupps
  • 3,284
  • 2
  • 16
  • 28
  • That caused more errors – Chrys Sep 07 '20 at 06:28
  • 1
    @Chrys Which errors specifically? I copied your example and verified this change so there should not be any other errors. – kingkupps Sep 07 '20 at 06:31
  • 1
    @Chrys The duplicates should answer your question and help explain what the differences are between a _static nested class_ and an _inner class_. Currently your `University` class (in the question) is of the latter type. – Slaw Sep 07 '20 at 06:32
  • test.java:10: error: modifier static not allowed here static public University() { – Chrys Sep 07 '20 at 06:35
  • there are 6 others that say: non-static variable this cannot be referenced from a static context – Chrys Sep 07 '20 at 06:36
  • The code you posted does not define `University` as a public class. Please post your actual code since the actual fix might be different between your example and your actual code. – kingkupps Sep 07 '20 at 06:37
  • @Chrys You don't put `static` in the constructor declaration—you put it in the _class_ declaration. – Slaw Sep 07 '20 at 06:41
  • Kingkupps and @Slaw Thank you both! It worked when I corrected that! – Chrys Sep 07 '20 at 06:44