Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner classes causing confusion

 
Lalit Kapoor
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic