• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static

 
HansLi
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read a book that say non-static inner class can have static member.I think it is wrong.Because inner instance must associate with outer class instance.Why the book say that.Who know reason?Thank you.
 
Harry Singh
Ranch Hand
Posts: 53
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hans,
You sound like you could write a better book on inner classes than the one you are reading. You are quite right and the book seems wrong. Only top level nested classes ( the only ones which are allowed to use a static keyword as part of their declaration ) can declare static memebers. What book is that ? You can tell all of us so we can avoid it ...
Thanks
 
Lahcen Mannou
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Please can someone explain why a static variable is not permitted in a non-static inner class ?
Thanks in advance
 
Mukesh Rathod
Ranch Hand
Posts: 32
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I am new member.
Well, the book seems to be correct!! Non- static inner class can have static member variable, provided they r final.
Try the following code:
class TestInnerClass{
class Inner{
public static final int i = 10;
public void aMethod(){
System.out.println("Static i = " + i);
}
}// end of inner class
public static void main(String args []){
new TestInnerClass().new Inner().aMethod();
}
}// End of outer class

Mukesh

Originally posted by HansLi:
I read a book that say non-static inner class can have static member.I think it is wrong.Because inner instance must associate with outer class instance.Why the book say that.Who know reason?Thank you.

 
Adrian Yan
Ranch Hand
Posts: 688
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correction:
Only package-level class, top-level nested class(static), and interface can define static memebers in their class.
------------------
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic