Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Creating the instance of static nested class.

 
Narasimha Rao B.
Ranch Hand
Posts: 205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Xiao Hu
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic