• 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

Why can't non-static inner classes have static members?

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bruce Eckel says in TIJ that fields and methos in ordinary inner classes can only be at the outer level of a class,

so ordinary inner classes cannot have static data, static fields, or nested classes.

What does this statement mean?

Its ok to know by trying out and running code to know that non-final static fields and static methods are not

allowed in non-static inner classes. I would like to know what the above statement by Eckel means. In other words,

why are non-final static members not allowed for inner classes.

For
//AnInnerClassWithStatic.java

public class AnInnerClassWithStatic{
class Inner{
public static final int NUMBER = 47; //This is ok
//public static int NOT_FINAL_NUMBER = 94; //JDK Error
//static void print(){ //JDK Error
void print(){
System.out.println("NUMBER: " + NUMBER);
}
}

public static void main(String [] args){
System.out.println("Inner.NUMBER: " + Inner.NUMBER );
//System.out.println("Inner.NOT_FINAL_NUMBER: " + Inner.NOT_FINAL_NUMBER ); //No such member
//Inner.print(); //Method not available

System.out.println();

Inner inner = new AnInnerClassWithStatic().new Inner();
System.out.println("inner.NUMBER: " + inner.NUMBER);
//System.out.println("inner.NOT_FINAL_NUMBER: " + inner.NOT_FINAL_NUMBER); //No such member
System.out.print("inner.print(): ");
}
}
 
Ranch Hand
Posts: 874
Android VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



I would like to know what the above statement by Eckel means. In other words,

why are non-final static members not allowed for inner classes.



Suresh,

Inner class are non static nested Classes which means they are associated with an instance of the Outer Class and have access to instance variables or methods of Outer class. Hence they cannot declare static initializers.

check out JLS8.1.3
reply
    Bookmark Topic Watch Topic
  • New Topic