Keep Simlling
i know that inner classes cant have static members but they can heve static final members but why this is allowed and again if an exam question comes should i answer that non-static inner classes can have static members or that they cant have.
Regards<BR>---------<BR>vadiraj<P><BR>*****************<BR>There's a lot of I in J.<BR>*****************
Originally posted by a hui:
class ToplevelClass {
private String msg = "Shine the inner light.";
public NonStaticInnerClass makeInstance(){
return new NonStaticInnerClass();
}
public class NonStaticInnerClass{
//static final int staticVar;
//static int staticVar;
private String string;
public NonStaticInnerClass(){ string = msg;} //constructor
public void printMsg() { System.out.println(string);}
}
}
public class Client{
public static void main(String args[]){
ToplevelClass topRef = new ToplevelClass();
ToplevelClass.NonStaticInnerClass innerRef1 = topRef.makeInstance();
innerRef1.printMsg();
ToplevelClass.NonStaticInnerClass innerRef3 = topRef.new NonStaticInnerClass();
}
}
The following example runs. It has a non-static inner class. If I add static or static/final variables I get a compile-time error. My answer is NO. You can not have static or constant fields in non-static inner classes.
AH
Test 094, IBM WID 6.0 cert
SCJP 1.2
SCBCD 1.3 Beta
SCWCD 1.4 Beta
SCMAD Beta
SCDJWS Beta
KS
Originally posted by bill bozeman:
The simple answer is that static final variables are compile time constants meaning the compiler will figure out that value and substitute in all of the code. You can't change the value so it is a constant and thus allowed in inner classes.
Static variables are not allowed in inner classes because you have to have an instances of the outer class in order to access the inner class but that goes against what static variables do. With static variables you don't have to have an instance of the class to access the static variabe.
So the answer is NO, you cannot have static variables in non-static classes, unless they are final.
Bill
You don't know me, but I've been looking all over the world for. Thanks to the help from this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|