File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regular Inner class

 
RAGU KANNAN
Ranch Hand
Posts: 103
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I refered K & B book it says
you can�t instantiate the inner class from a static method of the outer
class (because, don�t forget, in static code there is no this reference).

My question is the main method also a static method.
why this following code is not giving compilation error.

Thanks, Raghu.K

class MyOuter {
private int x = 7;
public void makeInner() {
MyInner in = new MyInner();
in.seeOuter();
}
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Inner class ref is " + this);
System.out.println("Outer class ref is " + MyOuter.this);
}
}
public static void main (String[] args) {
MyOuter.MyInner inner = new MyOuter().new MyInner();
inner.seeOuter();
}
}
 
Keith Lynn
Ranch Hand
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you are using an instance of the outer class to create the instance of the inner class.
 
Vishal Chawla
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can actually create an instance of inner class from a static method, just not the one referring to the current instance (using this)
See below,

 
bnkiran kumar
Ranch Hand
Posts: 176
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In static methods reference to an object is not available i.e this,super,MyOuter.this are not available,but we can create object of any class, you can see reference to outer class is not availabe in static main method that is why you created reference to outer class to create reference to inner class,you are not doing the same in makeInner method because reference to outer class is available in it.
remember for nonstatic methods reference of class's object in which that method is present is passed.

I hope this is clear to you.
 
Leo Velazquez
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On the above code wouldn't

public static void main(String [ ]args) {

new MyOuter( ); }

have given you the same print results?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic