File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static final int allowed in non-static inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static final int allowed in non-static inner class" Watch "static final int allowed in non-static inner class" New topic
Author

static final int allowed in non-static inner class

Rodge Thomas
Ranch Hand

Joined: Jul 25, 2002
Posts: 38
Here is an interesting question from Sun Guoqiao's mock exam 3, # 4
It is unclear why this is true:
"Non-static and static inner class can contain final static variable, which is the same as constant."
I thought non-static inner classes cannot contain static members?
Thank you for any insight.
----------
What is the output of trying to compile and run the following code?
(Select one correct answer)
-------------------
public class T004
{
public static void main(String args[])
{
System.out.println(A.i << B.j); //1
}
public static class A {
final static int i = 2; //2
}
public class B { //3
final static long j = 3; //4
}
}
--------------------------
A: The code does not compile due to line //1.
B: The code does not compile due to line //2.
C: The code does not compile due to line //3.
D: The code does not compile due to line //4.
E: The code compiles and runs with output 16
Answer:
: E
Explanation:
: The code just compiles and runs fine with output: 16.
Non-static and static inner class can contain final static variable, which is the same as constant.You can access them directly without creating the instance of the context class.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
The explanation given by Sun is correct. Being the value a constant known by the compiler, the compiler is able to replace each ocurrance of an access expresion to the static final field with the value itself. No creation of the outer object is needed. Thus, the requirement of accessing static fields without having to create instances of the classes in which they were declared is preserved.


SCJP2. Please Indent your code using UBB Code
 
Consider Paul's rocket mass heater.
 
subject: static final int allowed in non-static inner class
 
Similar Threads
Static Variables Shadowing : Q from Mock
inner class
scope
java
Resolve.........