1

class A is the outer class. Class B is an inner class of A, and class C is an inner class of B.

All three classes declare and initialize one static final variable.

This is the object in class A:

static final Object x = new Object(); 

class B:

static final Object x1 = new Object(); 

class C:

static final Object x2 = new Object(); 

The problem is that the variable in class A compiles fine, but in B and C the variable does not.

Error message:

the field can not be declare static; static field only declared in static and top level type

The String, and int in class B and C doesn't receive an error.

Complete code:

class A { static final Object x = new Object(); static final String s = "s1"; static final int y = 1; class B { static final Object x1 = new Object(); static final String s1 = "s1"; static final int y1 = 1; class C { static final Object x2 = new Object(); static final String s2 = "s1"; static final int y2 = 1; } } } 
2
  • Check this out: stackoverflow.com/a/5642851/3377857 Commented Mar 10, 2014 at 10:33
  • its working when remove static final Object x2 = new Object(); statements program compile and run also but when add this statement come compile time error Commented Mar 10, 2014 at 10:40

2 Answers 2

2

You can't have static fields/method in a regular inner classes, because, inner classes will work only with instance of outer classes.

So, static can't be there with instances.

But they can have compile time constants, check JLS 8.1.3. You x, x1, x2 are not compile time constants, while s1, s2, y1, y2 are compile time constants

Inner classes may not declare static initializers (§8.7) or member interfaces, or a compile-time error occurs.

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.

Sign up to request clarification or add additional context in comments.

3 Comments

I am curious as to how you can have an implicitly static nested class...
but when remove the these type statement static final Object x2 = new Object(); and program compile but also have static fields int and String
@user3184306 : Check my updated answer, inner classes can have static compile time constants
-2

You can just make the inner classes static.

static class A { static final Object x = new Object(); static final String s = "s1"; static final int y = 1; static class B { static final Object x1 = new Object(); static final String s1 = "s1"; static final int y1 = 1; static class C { static final Object x2 = new Object(); static final String s2 = "s1"; static final int y2 = 1; } } } 

Although obviously this will make some other things difficult.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.