File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Inner Class concept Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inner Class concept" Watch "Inner Class concept" New topic

Inner Class concept

harsh sahay

Joined: May 13, 2011
Posts: 13

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.

Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3152

Please CarefullyChooseOneForum >> Posted here as well.

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.

Mohamed Sanaulla | My Blog
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15084

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).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Inner Class concept
It's not a secret anymore!