Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inner Class reference 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 "Inner Class reference" Watch "Inner Class reference" New topic
Author

Inner Class reference

Yogesh Baraskar
Ranch Hand

Joined: Oct 07, 2007
Posts: 33
public class MyOuter{
private int outer=10;

public class MyInner{
public void show(){
System.out.println("in inner class" + "Outer var is :"+outer);
}
}

public static void main(String... args)
{
MyOuter mo = new MyOuter();
MyInner mi1 = mo.new MyInner(); //Line1
MyOuter.MyInner mi2 = mo.new MyInner(); //Line2

mi1.show();
mi2.show();

}

}


Is there any difference between line1 and line2, the way
they have declared inner class reference variable m1 and m2.

Both of them are compiling well and giving the same result.
Doug Slattery
Ranch Hand

Joined: Sep 15, 2007
Posts: 294
Hi Yogesh,

No, there is no difference. The compiler will let you declare it either way. You do not need to prefix the inner class with the outer class name.

Aloha,
Doug

-- Nothing is impossible if I'mPossible
Yogesh Baraskar
Ranch Hand

Joined: Oct 07, 2007
Posts: 33
Hi

I tried the inner class of my first post in another class as

public class TestInner
{
public static void main(String... args)
{

MyOuter mo = new MyOuter();
MyInner mi = mo.new MyInner(); //Line 3
}

}


now Line 3 is giving me compiler error .
This is a catch as Line1 is not giving error.

Dear Modirators , please provide some explanation to this behaviour.

Regards,
Yogesh
Doug Slattery
Ranch Hand

Joined: Sep 15, 2007
Posts: 294
Hi Yogesh,
Originally posted by Yogesh Baraskar:
Hi

I tried the inner class of my first post in another class as



now Line 3 is giving me compiler error .
This is a catch as Line1 is not giving error.

Dear Modirators , please provide some explanation to this behaviour.

Regards,
Yogesh


I may not have been as clear as I should've about my previous reply. If so, my bad. You don't need to prefix MyInner with MyOuter when declaring MyInner inside of MyOuter. Since your TestInner class is outside of both of those classes, this shorthand no longer applies. In this case, you must declare it as:


Aloha,
Doug

-- Nothing is impossible if I'mPossible
 
Consider Paul's rocket mass heater.
 
subject: Inner Class reference