File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inner class Doubts 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 "Inner class Doubts" Watch "Inner class Doubts" New topic

Inner class Doubts

Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
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 !!!

SCJP 6.0 96%

(Connecting the Dots ....)
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Have a look at here

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

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...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Adwin Lorance

Joined: May 31, 2010
Posts: 9
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

Joined: Jun 01, 2010
Posts: 618
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.

I agree. Here's the link:
subject: Inner class Doubts
It's not a secret anymore!