Cannot declare public static final String s = new String ("123") inside inner class

I tried to declare a class as below

class Outer{ private final class Inner{ public static final String s1 = new String("123"); public static final byte[] bytes = new byte[]{0x00, 0x01}; public static final String s2 = "123"; public static final byte byte1 = 0x02; } } 

In the above code, s1 and bytes are not compiled, and s2 and byte1 are compiled. If I put the whole declaration in an external class, it works fine. what i'm missing. Any help?

+6
java inner-classes constants final
source share
3 answers

Read the Java Language Specification, 3rd ed., §8.1.3.

An inner class is a nested class that is explicitly or implicitly declared static. Inner classes cannot declare static initializers (§8.7) or member interfaces.

That is why you cannot declare a new public static final String s1 = new String("123"); .

Inner classes cannot declare static members unless they are compilation of constant fields (§15.28).

This explains why you can do public static final String s2 = "123";

A static nested class can have static members.

+12
source share

cf Java Language Specification, Second Edition, §8.1.2

An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces

0
source share

Inner classes were designed to work in the context of an outer class , I think static variables will violate this rule.

8.1.2 Inclosing Enclosing Inner Classes and Instances

An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or members. Inner classes may not declare static members unless they are constant compile-time fields (§15.28).

0
source share

All Articles