• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Inner class object creation in static method

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic