• 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

Are the following the ONLY ways to instantiate a non static inner class

 
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. Outer.Inner i = new Outer().new Inner()
2. Outer o = new Outer()
Inner i = o.new Inner()
what about..........
3. Outer o = new Outer() //IS THIS OK ?!!
Outer.Inner i = o.new Inner()
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
looks to me that Option 3 is valid and option 2 is ont valid
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Depends on where you are trying to create an instance of the inner class. Here are two examples to show my point.
In the first examle, I create the OuterClass and have a main method of the OuterClass that I run.

In this case all three methods work.
For the second example, I have a new class that tries to create an instance of the inner class.

In this case, method 2 will fail since you can no longer referce variables of the class without an instance of the class, so you can't say InnerClass becuase it doesn't know what InnerClass is unless you say o.InnerClass.
So 1 and 3 are always correct and 2 may or may not be correct.
Bill
 
sarim raza
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks a lot Bill, that was just brilliant!
 
reply
    Bookmark Topic Watch Topic
  • New Topic