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

Inner class Doubts

 
Sahil Kapoor
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two doubts regarding Inner classes since i dint find or may be noticed the reason.

Doubt 1:- Why Method-local inner classes can use final Variables. I mean How ?

Doublt 2:- Why Method-local inner classes can only be abstract or final. What would be problem with other modifiers ???

Thanks !!!
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at here
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why Method-local inner classes can only be abstract or final. What would be problem with other modifiers ???

What is the use of other modifiers. Can you declare a local variable static or public or private?? No declarations inside of a method can be static or public or private or protected because it doesn't makes sense. Local variables are local to the method, so there is no point in them being public or private etc or even static for that matter...
 
Adwin Lorance
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hii .. just wanted to share why a method local inner class can access final variables...

As you must be knowing that when we compile a class having a method local inner class , the compiler makes 2 class files.
e.g. outer.class and outer$inner.class

Now imagine , if you could pass non final variables to a function inside the inner class. How will the JVM pass a variable from one class to a function in another class.
To solve this problem , the JVM makes a requirement that the developer mark the variable as FINAL.

How does it solve the problem?

when you mark a variable as final in the outer class , the compiler places a hidden variable (e.g. val$var ) in the compiled inner class file.
The value of this hidden variable and the final variable declared in the outer class will be same. And as it is final , it cannot change at the runtime. Also , the final variables has to be assigned before the compilation.

So problem solved.
I hope I was clear.
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below is code that demonstrates the discussion points. Note that the outer class does not reference the inner class. It references an interface that the inner class implements. Note also that although the inner class can not be declare public, its functions can.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic