• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Suresh S Nayar
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • 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(): ");
}
}
 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • 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
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!