Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner class object creation in static method

 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 348
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2120
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic