Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Class - Initialization Sequence

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initialization Sequence of this code:
- When outer is created in line 1 the constructor OuterTest(String id) is called
and „id“ of OuterTest is initialized to „STP“ and „Default Constructor
is printed to console.
- Then the instance „inner“ of the inner class is created. As inner class extends
The outer class the Default-Constructor of OuterTest is called and „NonDefault
Constructor“ is printed.
MY QUESTION is: Why didn’t get „id“ of OuterTest the value „Default“ which is
Set by the default constructor of „OuterTest“?
Instead the „Outer.Test.this.id“ keeps ist old value „STP“ from the creation of the
OuterTest-instance „outer“.


C:\Java\EigeneJavaProgramme>java OuterTest
NonDefault-Constructor
Default-Constructor
InnerTest STP
InnerTest Default
=> Question: Why is „OuterTest.this.id“ still „STP“ and not „Default“?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try the following code (warning: I didn't tested it...):

This should give you
false
true
Did that help?
 
Pete Lyons
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's see if I can explain what's going on. The key thing to focus on is that Inner is BOTH an inner class and a subclass. Because it's an inner class, it is automatically associated with an instance of it's outer class. Because it is a subclass, it inherits all it's superclass's properties. So when you construct the OuterTest in line 1, you get 1 instance with id set to " STP ". Now in line 2, you construct a new InnerTest via this new OuterTest, but remember that this new instance is a subclass of OuterTest, so it has it's OWN String id property, and that's what get's set to " Default ", leaving the outer instance's id unchanged. So from within the InnerTest class, OuterTest.this.id refers to the id property of the instance of Outertest that the current instance of InnerTest is implicitly associated with, and just id refers to the id property that the current instance of InnerTest inherits from the OuterTest class. Does that clarify things at all? This stuff can get very confusing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic