• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Class concept

 
harsh sahay
Greenhorn
Posts: 13
Eclipse IDE Java Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi...I tried to create a simple MyOuter class which holds an inner class called MyInner. As expected, two .class files where created after compilation as shown below:-

Can Someone please explain me as to why no constructor was created for MyOuter class as the compiler is supposed to insert it by default.
Secondly, what is the meaning of MyOuter paramMyOuter argument in MyOuter$MyInner constructor and how it helps.Please explain me the complete flow.
Thanks>>
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please CarefullyChooseOneForum >> Posted here as well.

Update:
I compiled the code you have provided and then used javap-



You see an extra field in the first one because the Inner class needs to have an reference of the outer class.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15447
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, harsh sahay.

When you create an inner class MyInner inside MyOuter, the Java compiler will indeed generate a class file named MyOuter$MyInner.class for the inner class. By the way, how did you get the output in the bottom half of your code - did you run javap or a similar tool?

I guess the compiler is smart enough to see that the constructor of your class MyInner contains no code and therefore you don't see it when you decompile the class. Try adding some code in there (for example just a simple System.out.println("hello");) and then you'll see the constructor when you decompile it.

About paramMyOuter: Each instance of a non-static inner class has a reference to the instance of the outer class that it was created in. The paramMyOuter is how the compiler passes this internally to the inner class. When you make class MyInner static, I think this will disappear.

(I've closed the copy in the other forum, let's answer the question in this forum).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic