Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inner class object creation in static method 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 object creation in static method" Watch "Inner class object creation in static method" New topic
Author

Inner class object creation in static method

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Fellow ranchers,
Here is the code:
public class Outer{
public class Inner{
}

static void aMethod(){
OuterClass ot=new OuterClass();
Inner in1=ot.new Inner(); //no problem

Inner in2=Outer.new Inner(); //error
}
}
Since there is not this reference in a static method, can we use class name Outer to do the job?
I am wondering why the second object creation failed? Any thoughts?
Victor
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Originally posted by victor gu:

public class Outer{
public class Inner{
}

static void aMethod(){
OuterClass ot=new OuterClass();
Inner in1=ot.new Inner(); //no problem

Inner in2=Outer.new Inner(); //error
}
}
Since there is not this reference in a static method, can we use class name Outer to do the job?
I am wondering why the second object creation failed? Any thoughts?
Victor

In your code, Inner is not static member of Outer class, you need to have a enclosing instance of Outer before you can create instance of Inner.


not so smart guy still curious to learn new stuff every now and then
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Originally posted by chichih Lin:

In your code, Inner is not static member of Outer class, you need to have a enclosing instance of Outer before you can create instance of Inner.

But why cannot we directly use class name to
do the job? Like we mention a static variable.
Any further thoughts?
victor
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
When creating an inner class (non static nested one) always is needed a reference to an instance of the outer class. The name of the class "Outer" is not an instance of it.


SCJP2. Please Indent your code using UBB Code
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Inner class object creation in static method
 
Similar Threads
inner classes
Anonymous Classes
Nested & Inner class
Inner class
Anonymous Inner Class