wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes bending the static rule?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "bending the static rule??" Watch "bending the static rule??" New topic
Author

bending the static rule??

nik rb
Greenhorn

Joined: Sep 25, 2005
Posts: 21
ok the thing is like ....this according to what i know.. a static code block cannot access instance variables.. but wat if instance variables are passed as parameters to a static member function?? will the rule bend?? will a static block be then able to access instance variables?? if yes then can anyone explain why this happens...
cheers
nik
Stian Almaas
Ranch Hand

Joined: Sep 22, 2005
Posts: 33
You mean something like this?



You cannot access instance variables from a static context, simply because to the static method the instance variables do not exist. You can pass the value of an instance variable to a static method but there would be no point. You would be better off defining a non-static method instead.
Robert Watkins
Greenhorn

Joined: Sep 20, 2005
Posts: 25
Yes, a static method can access the instance variables of a parameter (of the same type) that is passed in, or that it has obtained in another way (for example by creating it)

Originally posted by Stian Almaas:
You can pass the value of an instance variable to a static method but there would be no point. You would be better off defining a non-static method instead.


There are uses. Some that spring to mind are:
  • Factory methods (setting instance variables after the constructor)
  • Utility methods (e.g. extract common information from a parameter list)
  • Manipulating a static Singleton


  • In general, however, it's probably better to go with waht Stian said, and put the behaviour directly on the instance.


    Software is too expensive to build cheaply...
    Rick O'Shay
    Ranch Hand

    Joined: Sep 19, 2004
    Posts: 531
    > what if instance variables are passed as parameters to a static member function?

    What if the static value was loaded from a file, uplinked to a satellite, downloaded by a .NET application server and sent through a SOAP message to a process that called that static method? Tongue-in-cheek of course but the point is you do not have a reference to a static value; you have a parameter whose argument may have any number of additional references.

    Here's a less elaborate example. You cannot access private instance variables from outside the declaring class. Is it bending the rule to return a reference to it?

    private String secret;

    public String getSecret() { return secret; } // Bending rule? No.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: bending the static rule??