wood burning stoves 2.0*
The moose likes Java in General and the fly likes Inner classes causing confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Inner classes causing confusion" Watch "Inner classes causing confusion" New topic
Author

Inner classes causing confusion

Lalit Kapoor
Greenhorn

Joined: Jun 06, 2004
Posts: 20
Consider the following code:
class Outer{
static class Inner{
public Inner(){
System.out.println("Hello");
}
}
}
public class test{

public static void main(String args[]){
Outer.Inner i = new Outer.Inner();
}
}
The above code is valid and displays "Hello" when test.java runs. However, the following code:
class Outer{
//static class Inner{
class Inner{
public Inner(){
System.out.println("Hello");
}
}
}
public class test{

public static void main(String args[]){
Outer.Inner i = new Outer.Inner();
}
}
Gives "not an enclosing class: Outer" compile time error. Could anyone explain me the notion behind this. Why this is happening? Can only static inner classes be accessed using Outer.Inner notation?
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
In your second example, the inner class is no longer static. In order to create an instance of the inner class, it must be able to reference an instance of the enclosing class (to be able to access all of its variables and methods, etc). Thus, your code must be the following:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inner classes causing confusion
 
Similar Threads
inner class question
confused question
Inner Class
extending an inner class
Access to variables of enclosing class