This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Hands On Software Engineering with Python and have Brian Allbey on-line!
See this thread for details.
Win a copy of Hands On Software Engineering with Python this week in the Jython/Python forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

question about inner class instantiation  RSS feed

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I had a doubt about the instantiation of inner class�
From what I know instantiation of an inner class requires an object of outer class, except when the inner class is instantiated within the outer class itself.

public class outer{
class inner{
}

inner in = new inner();// (1) valid

public static void main(String []args){

inner in = new inner();// (2) not valid outer class object reqd.
}

}


On similar lines consider this example�


interface outer{
class inner{
}
}


public class outer2 implements outer{

public static void main(String args[]){

inner in = new inner(); // (3) valid

}
}

So my question is
1.Why cant we instantiate an inner class in a static method of outer class.
2.And why can we do the same in a class which implements the interface of the outer class.


Thanks in advance�
 
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good question!

In an interface, a nested class definition is implicitly static. (See JLS 9.5.) Therefore, although it is a "nested" class, it is not an "inner" class. (See JLS 8, JLS 8.1.3, and JLS 8.5.2.)

Because it is static, a static nested class can be instantiated without any enclosing instance. This makes it possible to instantiate from a static context, like main, where there is no implicit "this" referencing the current instance.

(Edit: Added JLS references.)
[ November 01, 2008: Message edited by: marc weber ]
 
What's that smell? Hey, sniff this tiny ad:
Programmatically Create PDF Using Free Spire.PDF with Java
https://coderanch.com/wiki/703735/Programmatically-Create-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!