• 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

Inner class.....

 
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
SOURCE: www.danchisholm.net



output is:

Prints: A0B0A1B1A1B2

why A1 prints twice here....?
Can you explain this?
 
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In new A().new B(); case it will print A0B0 is ok.
Then as in getCounter() and getInnerCounter() post increment operators are used.Then Counter and InnerCounter is set to 1.
But then A a1 = new A();constructor is used only once so,Counter only incremented once
and So A1 is printed twice
but as a1.new B(); // 3
a1.new B(); // 4
used, So new B() is used twice. And InnerCounter incremented twice.
 
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi GaneshKumar,

new A().new B(); // both constructor run here so you will get A0B0
A a1 = new A(); // Here only one constructor works and incremented name as A1 but not invoked.
a1.new B(); // only B constructor runs, so you get A1B1 and A constructor wont run here again since B only uses the refernce
a1.new B(); // same as previous only B works and so A1B2

Hope this clear you.

Preparing for scjp5
Preetha
 
reply
    Bookmark Topic Watch Topic
  • New Topic