It's not a secret anymore!
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regular Inner class" Watch "Regular Inner class" New topic

Regular Inner class

Ranch Hand

Joined: Dec 16, 2005
Posts: 103

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();
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();
Keith Lynn
Ranch Hand

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

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

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

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?
I agree. Here's the link:
subject: Regular Inner class
It's not a secret anymore!