aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Creating the instance of static nested class. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Creating the instance of static nested class." Watch "Creating the instance of static nested class." New topic
Author

Creating the instance of static nested class.

Narasimha Rao B.
Ranch Hand

Joined: Aug 26, 2002
Posts: 205
Hi,
As we all know, we can create the instance of static nested class directly with out having the object of top most class.
But can we create the instance of nested class using the object of outside class.
Just see the below examples,
public class Outer{
static class Inner{
}

public static void main(String args[]){
Inner inn = new Inner();//1
Inner inn1 = new Outer.new Inner(); // 2
Outer.Inner inn2 = new Outer.new Inner();//3
}
}

Why is compiler throwing the reference error at //2 and //3.
Can't i create the instance of the static nested class using the object of outside class?

Thanks,
Narasimha.
[ February 20, 2004: Message edited by: narasimha rao bandlamudi ]

Narasimha
Xiao Hu
Greenhorn

Joined: Jan 28, 2004
Posts: 9
Hi, Narasimah
Because class Inner is declared as static, when creating an instance, you must use the following syntax:
new (Enclosing Class Name).(Inner Class Name);
Change your codes to
Inner inn1 = new Outer.Inner(); // 2
Outer.Inner inn2 = new Outer.Inner();//3
Narasimha Rao B.
Ranch Hand

Joined: Aug 26, 2002
Posts: 205
Hi Xiao,
I know that, when creating the static inner class reference we should use the syntax,
new (Enclosing Class Name).(Inner Class Name);
But my doubt is why can't i use,
new (Enclosing Class Name).new (Inner Class Name);
Generally we call the static methods directly through the class name or by using one of the class reference. Here i am using the class reference to create the static nested class reference. what is the wrong here?
Thanks,
Narasimha.
fethi makhlouf
Ranch Hand

Joined: Feb 16, 2004
Posts: 50
Hi
i understood what do you mean Mr Rao,
i think you are thinking of the nested classes in the same wawy that top leve ones, it's little bit different:
static members in a class are callable either from class name or with any object name, but here we have a class as member, it should never be called as a member
Outer.Inner inn1 = new Outer().new Inner(); //Error
^ Qualified new of static class
i hope u understood me!
Yours


SCJP 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Creating the instance of static nested class.
 
Similar Threads
K&B doubt: Inner class name from static context of outer class
Inner class object creation in static method
Understanding Modifiers for Inner classes
Outside code as an Inner class
Inner classes