Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static final int allowed in non-static inner class

 
Rodge Thomas
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic