yagnya
yagnya

Reputation: 549

about non-static class in java

My doubt is when I run the following program

public class NonStatic
{
  class a
  {
    static  int b;
  }
}

The compiler is giving a error that "inner classes cannot have static declarations"

ok,then I made a change instead of "static int b" to "final static int b" its giving

same error but when I wrote "final static int b=10" means with initialization compiler

didn't complain,please can any body explain this what's the concept behind this.

Upvotes: 0

Views: 155

Answers (5)

user85421
user85421

Reputation: 29680

it is so by design, just see the Java Language Specification: Inner Classes and Enclosing Instances

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

Upvotes: 3

Santosh
Santosh

Reputation: 17893

Here is my take on this issue.

  1. Inner class is defined as a not static member of outer class and hence, it's instance cannot exist without the instance of outer class.
  2. The static fields of a class are accessible without creating an instance of that class.
  3. Now if you add a static field in the inner class, that means you can access that field without create the instance of inner class BUT according to #1 instance of inner cannot exist without an instance of outer class. So this is the conflict and hence the error.

TO CROSSCHECK : Just declare the inner class static and it will correct the error.

Upvotes: 0

Akshatha
Akshatha

Reputation: 597

If a field is static, there is only one copy for the entire class, rather than one copy for each instance of the class
A final field is like a constant: once it has been given a value, it cannot be assigned to again. hence when we r using final we have to assign the value to the variable.
have a look at the following link

Upvotes: 1

Alex Gitelman
Alex Gitelman

Reputation: 24722

final static int b=10 Is interpreted as a constant so compiler can just inline it. Similarly you can have static final constants in interface.

final static int b Is missing initialization,which is required for final member, so compiler can't quite figure what you want. Try putting following block right after it out of curiosity:

static {
  b=10;
}

Although it probably would not work...

Upvotes: 1

Novazero
Novazero

Reputation: 553

Its because a final static variable is a constant meaning it can't change at run time, while a static variable is not a constant and can change during runtime.

So in a class static variables aren't allowed in an inner class but the constants(final) are allowed.

Upvotes: 0

Related Questions