Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why can a static class not be instantiated via an object ?

 
Clay Chow
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know the java rules say inner static classes are instantiated via without an instance of the outer class, but ,

Why can't a static class be created from an instance of the outer class ?

From the below example,

why wouldn't lines 2a or 2b work ?
I would think lines 1 & 2a/b would be analogous to the way the lines 3 & 4 would work.



<CODE>
class Outer {


static class Inner {
static int number;
}
}

class Test {
public static void main(String[]ars) {
Outer.Inner a = new Outer.Inner(); // 1
Outer.Inner b1 = new a.Inner(); // 2a
Outer.Inner b2 = a.new Inner(); // 2b
int c = Outer.Inner.number; // 3
int d = a.number; // 4
}
}
<\CODE>
 
Campbell Ritchie
Sheriff
Pie
Posts: 49460
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the code button, not <> tags; the language is UBB not HTML. And make sure to maintain indentation inside the tags.
 
Harvinder Thakur
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why can't a static class be created from an instance of the outer class ?


Because static in java implies that you don't need an instance to access a static type member. You can use an instance with null value to invoke a static method of class. Hence going by that precedent a static class is also just like any other static member of a class and thus it is treated similarly.


Here you are invoking *new* on variable *a*. *a* is of type Outer.Inner and the compiler expects a type not a variable name.


Using new on static member is not a part of the syntax provided by the java compiler (even though you can use new on an Interface when defining anonymous inner classes).

I feel it's the syntax provided by the compiler more than anything else.
 
Clay Chow
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cool...thanks.

It just didn't seem intuitive for me initially, since you can access a static method from a instance, yet you cannot access a static class from the outer class instance.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic