• 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
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Please explain the output.

 
Greenhorn
Posts: 6
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
01. import Outer.Inner.InnerMost;
02. import Outer.*;
03.
04. class Outer {
05. int i;
06. class Inner {
07. Inner() {i++;}
08.
09. class InnerMost extends Inner {
10. InnerMost() {i++; System.out.println(i);}
11. }
12. }
13. interface InnerInterface {
14. void doSomething();
15. }
16. }
17.
18. public class Test implements InnerInterface{
19.
20. public void doSomething() {
21. System.out.println("done");
22. }
23.
24. public static void main(String[] args) {
25. Inner im = new Outer().new Inner().new InnerMost();
26. }
27. }


The output is 3, Why is it not 2??
 
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, understand that the instances of Inner and InnerMost share the instance field i with the enclosing instance of Outer. This is true no matter how many Inner or InnerMost instances we create.

Second, realize that whenever a class instantiated, the constructor of its superclass is called.

So first, the instance of Outer is created along with the i instance with a value of zero.
Then, the Inner instance is created. The Inner constructor increments i to 1.
Finally, the InnerMost instance is created, and before any of the commands in its constructor are executed, it calls the superclass constructor.
So i is now incremented twice more: once in the superclass constructor, and another time in the InnerMost constructor.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic