Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doesn't an Inner Class constructor propagate upwards by adding super() ?

 
Rahul Choudhary
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The output is super super sub inner

When Line 12 is executed, both the instance init blocks are executed after insertion of super().
So first MySub is instantiated on line 10 which inserts a super() call to MySuper() and hence super is printed followed by sub being printed. This propagation happens for normal class constructors. But finally when MyInner() is intantiated why isn't super() called for MySub and subsequently to MySuper()? Why isn't there a down to top propagation in the hierarchy? Isn't MyInner technically a subclass of MySub?

I hope my question is clear
 
Matthew Brown
Bartender
Posts: 4566
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rahul Choudhary wrote:But finally when MyInner() is intantiated why isn't super() called for MySub and subsequently to MySuper()? Why isn't there a down to top propagation in the hierarchy? Isn't MyInner technically a subclass of MySub?


No, MyInner isn't a subclass of MySub. Each MyInner is contained within a MySub, but there's no inheritance unless you add extends MySub.

So the calls propagate as usual, but it's only the Object constructor that gets called.
 
Rahul Choudhary
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great! Thanks Matthew
 
Himai Minh
Ranch Hand
Posts: 1254
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How the output is printed:
1. new MySuper () is called, it calls super() (the constructor of Object) and prints "super".
2. new MyInner() is called, it calls super() (the constructor of Object) and calls new MySub() (the initialization block).
3. In the constructor of MySub(), it calls super() (the constructor of MySuper and MySuper calls its super() as well.). It prints "super"
4. Next, in the MySub(), after calling super(), it prints "sub".
5. Go back to MyInner() contructor, it finishes its super() call and prints "inner".

Modify the code like this and you will see how it works:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic