Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

static nested classes  RSS feed

 
Harsha Vardhan Madiraju
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
class Test
{
static class inner
{
int x=10;
}
public static void main(String args[])
{
Test t = new Test();
Test.inner i = t.new inner();
System.out.println(i.x);
}
}
The above code is giving compile time error as
Test.java:12: qualified new of static class
Test.inner i = t.new inner();
My doubt is static nested class is just another static member of enclosing class, so why cant i access it using the object/reference of outer class just like i access any other static method using the references/objects of a class
 
Antoine Waugh
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
heyas,
your problem is
Test.inner i = t.new inner();
is attempting to create a new instance of a static class, which defeats the actual purpose of STATIC.
a static class is only created once, despite the number of instances created of your outer class..
just use
Test whatever = new Test();
System.out.println(new inner().x);
hope this helps
-twans
 
Gian Franco
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Harsha,
Originally posted by Harsha Vardhan Madiraju:
My doubt is static nested class is just another static member of enclosing class, so why cant i access it using the object/reference of outer class just like i access any other static method using the references/objects of a class

As with other static members you don't need an instance of the outer
class to access a static inner class. This is more of a mandatory
requirement if you want to instantiate the static class, because the
syntax differs from normal inner class instantiation, namely:
OuterClassName.NestedClassName n = new OuterClassName.NestedClassName()
so you need to use both class names and not the reference to an
instance of the outerclass.
Greetings,
Gian Franco
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!