wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes newbie's question about inner class existence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "newbie Watch "newbie New topic
Author

newbie's question about inner class existence

SkyGriller tian
Greenhorn

Joined: Jan 27, 2012
Posts: 8
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

Joined: Jan 28, 2012
Posts: 34
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

Joined: Jan 28, 2008
Posts: 5575

Hi,

you should read this interesting story
SkyGriller tian
Greenhorn

Joined: Jan 27, 2012
Posts: 8
thanks for the answers above!! i'm clear now.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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.
 
 
subject: newbie's question about inner class existence
 
Similar Threads
confused question
Inner classes
Inner Class
Inner class
static inner class