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

Doubt

 
sravanthi pulukuri
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class OuterTest {

String id ;

OuterTest ( ) {
this . id = " Default " ;
}

OuterTest ( String id ) {
this . id = id ;
}

class InnerTest extends OuterTest {

void doSomething ( ) {
System . out . println ( OuterTest. this . id ) ;
}
};

public static void main ( String args [ ] ) {
OuterTest outer = new OuterTest ( " STP " ) ;
InnerTest inner = outer . new InnerTest ( ) ;
inner . doSomething ( ) ;
}
};
can you explain me why it is giving output as STP
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I would also like to know what is happening there!



Thanks and Regards,
cmbhatt
 
sravanthi pulukuri
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
something is going on in the inside the method of inner class
there i was struck up
Please help me out
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's pretty straightforward.

An OuterTest object named outer is created with the parameter " STP".

This object is then used to create an instance of it's inner class, InnerTest.

InnerTest extends OuterTest so it inherits the field id. But that doesn't really matter.

The important thing is that in the method doSomething, you are using the syntax OuterTest.this.

An inner class can access it's outer class's this with that syntax.

So you are printing out the field id associated with the instance of OuterClass that was used to create the instance of the inner class.
[ March 30, 2007: Message edited by: Keith Lynn ]
 
sravanthi pulukuri
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
soory for the delayed reply the it should print STP na
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic