*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regular Inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regular Inner class" Watch "Regular Inner class" New topic
Author

Regular Inner class

RAGU KANNAN
Ranch Hand

Joined: Dec 16, 2005
Posts: 103
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

Joined: Feb 07, 2005
Posts: 2367
Because you are using an instance of the outer class to create the instance of the inner class.
Vishal Chawla
Greenhorn

Joined: Apr 06, 2006
Posts: 28
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

Joined: Mar 02, 2006
Posts: 176
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.


Kiran Kumar.
Leo Velazquez
Greenhorn

Joined: Apr 27, 2006
Posts: 13
On the above code wouldn't

public static void main(String [ ]args) {

new MyOuter( ); }

have given you the same print results?
 
wood burning stoves
 
subject: Regular Inner class
 
Similar Threads
why private member variable of inner class can't be accessed by its outer class but mehod can be?
Inner class
Inner Classes Q
why private member variable of inner class can't be accessed by its outer class but mehod can be?
inner class instantiation from outside the the outer class