aspose file tools*
The moose likes Beginning Java and the fly likes Why can a static class not be instantiated via an object ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why can a static class not be instantiated via an object ?" Watch "Why can a static class not be instantiated via an object ?" New topic
Author

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

Clay Chow
Ranch Hand

Joined: Nov 09, 2008
Posts: 35
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

Joined: Oct 13, 2005
Posts: 38756
    
  23
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

Joined: Jun 10, 2008
Posts: 231
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.


thanks
Harvinder
Clay Chow
Ranch Hand

Joined: Nov 09, 2008
Posts: 35
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why can a static class not be instantiated via an object ?