• Post Reply Bookmark Topic Watch Topic
  • New Topic

Member inner class  RSS feed

 
prateek shaw
Ranch Hand
Posts: 46
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have one doubt regarding member inner class with static variable and static method. As i know that we can not define static variable or static method inside the member inner class.
I have tried this and as expected compiler has given error.

However when i have defined final static variable, it did not give any error. However when i have tried to put static and final in method then it did not compile. Code is below.



The reason why java did not allow to define static method and static variable for member inner class, because we can not have access of member inner class until you have instance of outer class. Since this is depend on instance therefore they prohibited to define this. Also same time we have option to define static inner class , in which we can define method and variable as a static.


But my question why they have allow us to define static final instance variable inside the member inner class ?
 
Andrea Binello
Ranch Hand
Posts: 62
5
Eclipse IDE Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
prateek shaw wrote:But my question why they have allow us to define static final instance variable inside the member inner class ?

Because as Java Language Specification 8 states in §8.1.3:

"It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable"

And a static final variable indeed is a "constant".
 
prateek shaw
Ranch Hand
Posts: 46
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for reply.
 
Henry Wong
author
Sheriff
Posts: 23291
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andrea Binello wrote:
And a static final variable indeed is a "constant".


First, compile time constants are a bit more complex than that... see this thread...

https://coderanch.com/t/454384/java/compile-time-constant


And regardless, have a cow for your response.

Henry
 
Andrea Binello
Ranch Hand
Posts: 62
5
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I had to be more precise. In an inner-class only compile time constants can be declared.


P.S. And thanks for the cow.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!