File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes method-local inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "method-local inner class" Watch "method-local inner class" New topic

method-local inner class

Brian Smithhfds

Joined: May 17, 2011
Posts: 4

This is code from a question on an SCJP practice test. The answer output is Zippo, but I don't understand why it compiles. I have notes that say a method-local inner class can only be instantiated in that method. If an attempt is made to use it outside the method, it won't compile. Did I misunderstand the book I took notes from or am I missing something with this code? Thanks.

[HENRY: added code tags]
Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
I'm not familiar with term "method-local inner class" -- there's always something to learn.

In any event, it seems that this class is defined and used within the method main(). What's the problem?

Brian Smithhfds

Joined: May 17, 2011
Posts: 4
Oh, you're right, it is. For some reason I was thinking it was outside of main. I was misreading the code, now I don't know how I missed it. Thanks for the help.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

Welcome to the Ranch, Brian!

Yes, you can define classes inside methods like that. It's a feature of Java that isn't used very much, and I guess many Java programmers don't even know that it is possible. The normal rules for scoping apply: class Horse will not be visible outside the { ... } of the method in which it is defined.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: method-local inner class
It's not a secret anymore!