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

method-local inner class

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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]
 
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I miss the old days when I would think up a sinister scheme for world domination and you would show a little emotional support. So just look at this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic