FunnyFunkyBuggy
FunnyFunkyBuggy

Reputation: 613

Declaring a static variable in a non-static class in Java

I am new to java. I am currently reading some articles about static variables. When I am trying to implement my learnings, I encountered a problem about static variables. Here is the first code sample.

public class Human {
    // in Human.java
    public static int population = 0;
    public static void main(String[] argv) {
         System.out.println(population);
    }
}

This code works fine and the outcome is 0. But for the following code, I wasn't allow to compile it.

public class Human {
    // in Human.java
    public class Charlie extends Human {
        public static int number = 0;
    }

    public static void main(String[] argv) {
         System.out.println(new Human().new Charlie().number);
    }
}

An error occurred: The field number cannot be declared static in a non-static inner type, unless initialized with a constant expression

I am confused with this situation. For the first code sample, my Human class is non-static and I was allowed to declare a static variable inside it. How come I can't do the same for my second code sample.

Any help would be appreciated. Thanks. :)

Upvotes: 4

Views: 6177

Answers (1)

bNd
bNd

Reputation: 7640

Try with public static final int number = 0; because Java does not let you define non-final static fields inside function-local inner classes. Only top-level classes and static nested classes are allowed to have non-final static fields.

From the JLS section 8.1.3:

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.

Other way to make inner class static and access it

public class Human {
    // in Human.java
    public static class Charlie extends Human {
        public static  int number = 0;
    }

    public static void main(String[] argv) {
         System.out.println(new Human.Charlie().number);
    }
}

Upvotes: 5

Related Questions