Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Inner class with static member

 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I had read that read that regular Inner calsses (which are not static,method-local or anonymous) can't have static members . But when i compiled the following code :
class Z{
class A{
static final int e=1;
}
}
It compiled fine when i remove the final keyword the code doesn't compiled.


Pls. Clarify it.

Mohit Agarwal.
Would be SCJP.
"The will to win is worthless if u do not have the will to prepare"
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Inner class(non static nested class) can have cannot have static members until they are compile time constants

In this case,
static final int e = 1 is a compile time constant. So it is accepted.

If it had been,
static int e=1(without final), it would give an error.
or
static final int e(without any defintion), it would give an error.

Hope this helps!

sanjana
 
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Mohit,
when we declare a regular inner class then it can't contain static variables,static methods or interfaces(becoz nested interfaces are implicitly static).
The only exception to this rule is when the static variable is declared final and whose value is determined at compile time.
hence when the variable is declared both static and final in a regular inner class ,both declaration and initialization must happen in the same statement i.e the following code fragment gives error
10. static final int i;
11. i=10;
Hope this helps.
 
It's just like a fortune cookie, but instead of a cookie, it's pie. And we'll call it ... tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic