This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "inner class" Watch "inner class" New topic

inner class

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
class outer
protected class inner
public inner()
{ System.out.println("in inner");
private inner p1;
{System.out.println("in constructor of outer class");
p1=new inner();//1
public static void main(String a[])
{ new outer(); }
AT line 1 i.e even before an object of outer class is created
inner class object is created.How is it working??? since
innerclass can be created after outer class object is created.
ricky gonzalez
Ranch Hand

Joined: Jun 30, 2000
Posts: 167
Does an object of an inner class have to be created after an object of an outer class is created? Actually, you can co-create them at the same time. ie. new Outer.Inner();, which is similar to your case I think.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Yes, Rickey.The inner class cannot exist on its own.It is
always binded with the outer class.So,in ur code
it should be new outer().new inner().Please correct me
where i am wrong.
Amar Srivastava

Joined: Jul 25, 2000
Posts: 3
Actually one could create inner classes in both the ways
1) to create STATIC inner classes: new Outer.Inner()
2) otherwise: new outer().new inner()
The position of the code DOES not determine when it would be executed. JAVA has the entry point at function "main", at main you called new outer() so the ctor for outer would be called and then the code for inner's ctor would be called which is perfectly consistent with the way outer and inner are supposed to work.
[This message has been edited by Amar Srivastava (edited July 26, 2000).]
I agree. Here's the link:
subject: inner class
Similar Threads
Inner class
class types
naming : package, inner classes
Does static variables of static inner class will be loaded as soon as outer class name is countered.
Question on inner classes