Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: field name cannot be declared static

public class Application {
    public static void main(String[] args) {
        final class Constants {
            public static String name = "globe";
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Constants.name);
            }
        });
        thread.start();
    }
}

Compilation Error: The field name cannot be declared static in a non-static inner type, unless initialized with a constant expression

Solution to this?

like image 692
Pramod Ravikant Avatar asked Aug 30 '13 06:08

Pramod Ravikant


1 Answers

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.

If you want a static field in your Constants class, put it at the Application class level, like this:

public class Application {
    static final class Constants {
        public static String name = "globe";
    }
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Constants.name);
            }
        });
        thread.start();
    }
}
like image 156
Sergey Kalinichenko Avatar answered Sep 19 '22 05:09

Sergey Kalinichenko