BUG: Inner Compile-Time Constant String Members Not Permitted (325740)



The information in this article applies to:

  • Microsoft Visual J++ 6.0
  • Microsoft Visual J# .NET (2002)

This article was previously published under Q325740

SYMPTOMS

When you define a static final string member in an inner class, such as the following
public class Outer 
{
  private class Inner 
  {
    static final String  NAME = "Bob";
  }
}
				
you may receive the following error messages in the Visual J# .NET compiler:
error VJS1176: Cannot declare field 'NAME' static in an inner class
-or-
error VJS1175: Inner class 'Inner' contains a static initializer

RESOLUTION

Future versions of the Visual J# .NET compiler are expected to support static final string member types in inner classes. See the "More Information" section for possible functional equivalent workarounds.

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

MORE INFORMATION

The Java language specification permits compile-time primitive type constants in inner classes, including string literals. However, neither the Visual J++ 6.0 nor the Visual J# .NET compilers support this feature.

To work around the problem, do not use the static modifier, and use instance variables for string constants in inner classes. You can also define static string constants in an interface that can then be exposed on the inner class. The following is a code sample for both scenarios:
public class OuterClass
{
  public interface IStringConstant
  {
    String NAME = "Robert";
  }

  private class Inner implements IStringConstant
  {
    final String name = "Bob";
  }

  public static void main(String[] args)
  {
    System.out.println("static final string on interface:  " 
      + Inner.NAME);

    System.out.println("final instance string on class:  " 
      + new OuterClass().new Inner().name);
  }
}
				

REFERENCES

See section 8.1.2 of the Java language specification for more information about compile-time constants in inner classes.

Modification Type:MajorLast Reviewed:1/19/2004
Keywords:kbbug kbnofix KB325740