• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

method-local inner class

 
Brian Smithhfds
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

rc
 
Brian Smithhfds
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic