• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

static final int allowed in non-static inner class

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
He's giving us the slip! Quick! Grab this tiny ad!
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic