• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

newbie's question about inner class existence

 
SkyGriller tian
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi everyone.
i read some lines from oracle official tutorial:

"An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. The next figure illustrates this idea."

so, i think before i instantiate a inner class i should create an object of (or instantiate) the outer class. but the fact is i directly instantiate the inner class without any error.Could anyone explain the difference between tutorial and my experience?

much thanks!

MY CODE HERE

public class Problem {


static class Inner {

void testMethod() {
System.out.print("aString");

}
}
public static void main(String[]args){
Problem.Inner innerA=new Problem.Inner();
innerA.testMethod();
}
}
 
Viktor Kubinec
Ranch Hand
Posts: 34
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

there is difference between "regular" (not static) and static inner classes. The rule you have written here is for the regular inner classes. So if you declare your inner class as non static, your code will not compile and you will need to create instance of outer class in order to instantiate the inner class. Regular classes have access to all outer members, static classes can access only static members.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

you should read this interesting story
 
SkyGriller tian
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the answers above!! i'm clear now.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Viktor Kubinec wrote:Hi,

there is difference between "regular" (not static) and static inner classes. The rule you have written here is for the regular inner classes.


Which are in fact not inner classes at all. Just nested classes. An inner class is, roughly, a non-static nested class, or a nested class with an outer "this", although the JLS seems slightly inconsistent if you drill down through all the gory details.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic