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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With