4

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. :)

0

1 Answer 1

5

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

other way would be making the charlie class static. might be worth mentioning
I see. Are there any reasons for Java to have this restriction? Does this implies that the Java VM treats inner class different from outer class?
@FunnyFunkyBuggy because Inner class is instance of class. There is no meaning to have static variable in instance itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.