Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bending the static rule??

 
nik rb
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
     
    Rick O'Shay
    Ranch Hand
    Posts: 531
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    > 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.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic