permaculture playing cards*
The moose likes Beginning Java and the fly likes Invoking static member classes from separate class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Invoking static member classes from separate class" Watch "Invoking static member classes from separate class" New topic
Author

Invoking static member classes from separate class

Graeme Byers
Ranch Hand

Joined: Apr 16, 2004
Posts: 127
GBTest1 works for non-static member classes.
It can invoke contentsMethod() via parcelMethod() or directly from main.

Now lets make Contents into a static member class :
1. static class Contents { }
2. private static String parcelContents = "books" ;

Compile - Java does not like new Contents() , get rid of new.
Compile - Java thinks .Contents() is a method , lose ()
Compile - Java thinks Contents is a variable
Try p.Contents.contentsMethod() ;
No - non-static method from static context
(Java has some differing views on whether a method (not marked static)
in a static class is static - will not let you access an instance
variable from one)
Coding static contentsMethod() {} does not help.

Lose Methods 2a and 2b and Method 1 works.

Does this mean that if main is not in the same class (GBTest1) as the outer class (Parcel)of a static member class (Contents) then it can never invoke a Contents method directly ?

Thank you



[ December 17, 2008: Message edited by: Graeme Byers ]

[ December 17, 2008: Message edited by: Graeme Byers ]
[ December 17, 2008: Message edited by: Graeme Byers ]
Graeme Byers
Ranch Hand

Joined: Apr 16, 2004
Posts: 127
This works :
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38513
    
  23
The fact that it compiles doesn't mean that it works. If you have "books" as a static field in the ParcelContents class, then it implies that all your parcels contain "books" and nothing else; if you manage to change it to "socks" then all your book parcels will say they contain socks.

Your contents field should be an instance field, then you can have parcels of books and parcels of socks. You should set it up in the constructor. And forget about inner classes; they simply add another level of confusion at this stage.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Invoking static member classes from separate class