• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with Inner Class  RSS feed

 
MrKamal Joshi
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was experimenting with inner class and got some problems

Q1)Line 24.Why we have to redeclare Name inside inner as it was already been declared in outer class and members of outer class are also members of inner class?
Q2)Line 8 or 27 after omitting // and running the program i came across a weird output like that of infinite loop.What's that?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the first one - you don't have to redeclare Name (and it really should be name, not Name!) in the inner class unless you want the inner class to have its own copy. But, I suspect the problem you had was with referring to this.Name? Remember that in the inner class, this points to the inner class. So this.Name can't point to the variable belonging to the outer class.

You could have got round it by just using Name by itself, or by using Outer.this.Name.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you uncomment line 27, then every time you create an InnerNonStatic object, that will create another one, which will create another one.....See the problem?
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
MrKamal Joshi wrote:
Q1)Line 24.Why we have to redeclare Name inside inner as it was already been declared in outer class and members of outer class are also members of inner class?

but outclass member is still different from inner class member for example LinkedList has Node as inner class and Node has reference and value fileds! ofcourse you can declare variable as same as outerclass variable name. but as much possible give another name(avoid masking/shadowing)

MrKamal Joshi wrote:
Q2)Line 8 or 27 after omitting // and running the program i came across a weird output like that of infinite loop.What's that?

It is an expected output! constructor calls itself again since you are calling the constructor from instance filed declaration(initialization block)
 
MrKamal Joshi
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seetharaman Venkatasamy wrote:
It is an expected output! constructor calls itself again since you are calling the constructor from instance filed declaration(initialization block)

This means in a class anything outside the method will be implicitly under a initialization block.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!