Sign in to follow this  
Xer0botXer0

Methods accessing each others variables

Recommended Posts

Xer0botXer0    120

Hi guys,

So I'm wondering why cant I reference a value or even access a value that's in a method from another method.. like so

 

public class Main {

    public static void main(String arg[])
    {
                
        String bob = "bobby";
        compute();
    }

    public static void compute() 
    {
    main.bob = "yoyo";
    
    }
}


 

I don't know if I'd ever want to do this, but I'm just curious, does this mean that there's simply no other way to modify the variable values of a method without providing it with values through invoking the method ?  

 

So in the following way I can basically set what values (true to the predefined data types) these argument variables will have..

public class Main {

    public static void main(String arg[])
    {
        
        String one = "Ping",two = "Pong";
        String Result = "";
        Result = compute( one,  two);
        System.out.println(Result);
    }

    public static  String compute(String first, String second) 
    {
        
        String joined = first + " " + second;
    return (joined);
    
    }
}

 

What if instead of this I have

 

        String joined = first + " " + second;

        String joined_2 = third + " " + forth;

        String Altogether = joined + joined_2;
    return (Altogether);

 

So say i get to the first line in that code and suddenly want to change a value in the second line, would that be possible ? 

 

Okay crappy example, I suppose parameters are then the only manner available for methods to get values from the invoking method ? 

 

Share this post


Link to post
Share on other sites
jpetrie    13154

Most languages (including C# of Java, which you appear to maybe be using) are not designed this way; they simply don't consider a method to have local instance variables and state associated with it that persists outside the temporary memory reserved for that method when it is executing. In fact, I don't know any languages (offhand) that would explicitly permit you to do what you wrote the initial example for.

Some languages do have "static" local variables in methods, but they're usually just like globals with a narrower lexical scope; explicitly narrowed so you cannot refer to them like you're suggesting.

So yes, there's no way to modify the value of a variable in a method without passing a value to that method (or similar) to indicate how the method should initialize the variable. The (non-static) variables you're declaring in a method are local: they come into being when the method is called, and exist only for the duration of the method's execution. Then they are (effectively) destroyed when the method ends. So there's nothing to "modify" outside that method.

45 minutes ago, Xer0botXer0 said:

Okay crappy example, I suppose parameters are then the only manner available for methods to get values from the invoking method ? 

 

If you want to "share" information you need to either pass it from method to method or store it as a member of the containing class. Those are generally your two best options, and there are cases where either choice is the better one. It depends on what you're doing.

You can also create globals and share information that way, but this is generally not a great option (and not directly supported by C#, but you can do things to create effective globals that share all the same problems anyhow).

Share this post


Link to post
Share on other sites
Xer0botXer0    120

Thanks, well I'm using Java. And I was thinking of objects in Game Makers GML, where variables of objects can be referenced  and modified.

But I've come to realize that methods in Java are similar to Scripts in GML which are temporary. So what I'm looking for I think would be classes. I recall now that I can access variables/arrays and such from one class to another using the classname.variablename line. 

I'm mainly trying to get a better image of what everything can and cant do while studying. 

Share this post


Link to post
Share on other sites
jpetrie    13154
18 minutes ago, Xer0botXer0 said:

Thanks, well I'm using Java. And I was thinking of objects in Game Makers GML, where variables of objects can be referenced  and modified.

 

Variables stored in objects can be referenced and modified in Java. Methods, however, are not objects in that sense.

19 minutes ago, Xer0botXer0 said:

So what I'm looking for I think would be classes. I recall now that I can access variables/arrays and such from one class to another using the classname.variablename line. 

Yes. A class describes a type of object, and you can create instances of that type. Those instances are the kinds of objects you can read and write the member variables of.

Share this post


Link to post
Share on other sites
Xer0botXer0    120

So I did a bit of further reading and from what I can see, There are Instance fields/Instance methods and there are Class fields/Class methods, The class fields and methods are unique to each instance(object) of a class. Where Class fields and methods are somewhat global and are recognized by their static modifier in their definition. 

I can modify the instance fields/methods by storing a reference to the object in a variable.

But I've got a question regarding the Static types, I'm going to test this out now anyway for the practice because as someone said before it helps to try it out myself too. But I like the forum since you can sometimes get more information which is apart of what helped me progress in Java quite a bit. 

If I create a class called Fruit, and within the class I create a class variable called fruit_Type, then create four objects of class Fruit, I don't use a for loop rather just one after another, in each case I set the fruit_Type class variable to something different like "mango", "orange", "tomato(is tomato a fruit lol)", "guava". 

If I then iterate through all four objects, will they have unique values for fruit_Type, can I even access a static field(var) that way ? Going to test this out now. 

 

From my understanding the purpose of a class field is to store a value that all objects of that class will share, the purposes of instance fields is that the instance values can be unique, instead of having a basket.java of mangoes I'd have a basket of a variety of fruit.

 

Okay I tested it.

public class Main {
    
    public static void main(String arg[])
    {
        
        Fruit f1 = new Fruit();
        f1.fruit_Types = "Banana";
        
        System.out.println(f1.fruit_Types);
        System.out.println("");
        
        Fruit f2 = new Fruit();
        f2.fruit_Types = "Guava";
        
        System.out.println(f1.fruit_Types);
        System.out.println(f2.fruit_Types);
        System.out.println("");
        Fruit f3 = new Fruit();
        f3.fruit_Types = "Grape";
        
        System.out.println(f1.fruit_Types);
        System.out.println(f2.fruit_Types);
        System.out.println(f3.fruit_Types);
        System.out.println("");
    }
}

 

Fruit.java :: public static String fruit_Types = "Lemon"; produces:

  • Banana
  •  
  • Guava
  • Guava
  •  
  • Grape
  • Grape
  • Grape

while without the static modifier it becomes an instance field and produces:

  • Banana
  •  
  • Banana
  • Guava
  •  
  • Banana
  • Guava
  • Grape

 

So I'm happy with the findings. :D

Edited by Xer0botXer0

Share this post


Link to post
Share on other sites
Kylotan    10007

Static, in this context, does mean "shared across all instances of this class". Everything else has its own copy per instance. Good work on testing for yourself and verifying your understanding. Try and avoid statics unless you absolutely need something shared, however.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By grumpyOldDude
      As my project is beginning to take shape, most of the problems I've encountered, I've been able to solve, but this latest one cunningly beats me, not because of any complexities but  because I don't know whats going on under the hood of the parser.
      I am using a pattern matcher() Pattern.compile("\\d+");  - (in JAVA) - to extract and read floats,   but there were problems as white spaces are being interpreted as 0.0
      808.00.0472.00.036.00.0202.00.018.00.024.00.0 782.00.096.00.036.00.0202.00.018.00.024.00.0 909.00.01028.00.036.00.0202.00.018.00.024.00.0 931.00.01149.00.036.00.0202.00.018.00.024.00.0 but should, correctly, be something like this 808.0 472.0 36.0 202.0 18.0 24.0 782.0 96.0 36.0 202.0 18.0 24.0 909.0 1028.0 36.0 202.0 18.0 24.0 931.0 1149.0 36.0 202.0 18.0 24.0 It was wrong because it was making white space to be 0.0 As said It was wrong because it was making white space to be 0.0
      My quick fix was to use an if statement that exclude 0.0.  
      Well I got away with it until the inevitable began to happen,- some of the real data started turning out to be 0.0, so my if statement was excluding the  real data from being read.  Any help on how to get this fixed?  I need white space to be read as white space not as 0.0 
      public void readDataFromSelectedTextFile( File fPathplusName ){ List<Float> numbers = new LinkedList<Float>(); try { bufferedReader = new BufferedReader(new FileReader(fPathplusName)); while ((stringObjectData = bufferedReader.readLine()) != null){ Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(stringObjectData); while (m.find()) { numbers.add(Float.parseFloat(m.group())); } } ListIterator<Float> floatIterator = numbers.listIterator(); int i=0, t=7, n=0; float s, size=0; while( floatIterator.hasNext() ){ if( (s = floatIterator.next()) > 0 ){ ... ... plenty of good coding here ... ... } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }/**/ }  
    • By JesterCall
      First of all sorry, for my terrible writing im not good with it, but there is no need to hold back with your answers i only have problems when it comes to writing. 
      I started to write my own 2D Game Engine in Java for practice(and for fun) reasons. Until now i've made very good progress but i got a problem, which i got stuck on. 
      I started to build a basic tile picker (left click: setTile | right click: getTile). So far so fine, but here is the problem. The further away my mouse gets from the upper left corner of the screen, the more inaccurate the tilepicker gets.
      In the picture, you can see the overall tile i clicked on (black cross) and the accurat point (orange dot). This would get me the blue tile underneath.
       

       
      This is the code i used to translate the mouse coordinates to tile coordinates. 
      if(input.mouseleft.isClicked()) { tx = (int) (Math.floor(world.getCamera().getX() + input.getMouseX()) / world.getTileSize()); ty = (int) (Math.floor(world.getCamera().getY() + input.getMouseY()) / world.getTileSize()); // Checks if the coordinates are within the tilemap if(tx >= 0 && tx <= world.getWidth() && ty >= 0 && ty <= world.getHeight() ) world.setTile(holdtileid, tx, ty); }  
      I hope somone can help me and thanks in advance.
       
       
    • By janek29
      Hi,
      I want to present my game called "What's that?". I developed it using Android Studio.
      Download from here: https://play.google.com/store/apps/details?id=com.threemgames.whatsthat&hl=en
       
      Youtube video gameplay:
       
       

       
       
      It contains Google Play leadboards so you can compare your score with your friends.
      It is an easy game in which u have to use your head and guess the names of 50 objects - things, animals or activities.
      Use your imagination and on the basis of a few strokes deduce what may be in the drawing.
      Open your mind because it will allow you to put together lines, dots and bows into one. When you are sure of what the drawing represents, enter the name using the letters at the bottom. If you have doubts or can not guess, use the tips. So to the work, wake up your mind, duck your mind in the missing elements and solve the mystery. Let the imagination be with you!
       
      * 50 different puzzles
      * An amazing quiz that stimulates the imagination
      * Different degrees of puzzle difficulty in the quiz
       
      It is FREE!
       
      I am waiting for your comments .
       
      Please, give me feedback. If you notice any bugs please tell me .
       
      Thanks !
    • By mungee
      https://www.youtube.com/playlist?list=PLx2OWCj5oxNPuqz2o3Tk8exOQtAAtIeRd

    • By imontheverge
      Im trying to create a simple " give order to Sprite, make Sprite do thing" game much like rimworld or oxygen not included.
      So far I have two controllers type objects, on for the player and one for each Sprite. When a Sprite is selected, the player controller takes a reference of the Sprite and sets a Boolean variable hasMoveOrder to true when the player clicks on a spot.
      My code right now is filled with if/else statements in order to get this to work. Once I add more work orders like digging, building, etc, a thousand if statements starts to get sloppy. The question is what kind of data structure or algorithms can I use to make this more efficient? Would an enumeration of the Sprite states be fine and just switch through them when the Sprite gets a new work order? Or would something more complex like a state machine make sense?
  • Popular Now