Sign in to follow this  
Xer0botXer0

Methods accessing each others variables

Recommended Posts

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

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

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
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

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

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  

  • Announcements

  • Forum Statistics

    • Total Topics
      628298
    • Total Posts
      2981890
  • Similar Content

    • By Giannis Marinakis
      Hello everyone!
      I have a GitHub repository on which I'm developing a Open Network Library for Java Developers and I'd like to share it so more people come in and contribute. Till now the repo is being developed only by me so the library is not 100% bug free. I'd really like this repo to be famous and got people working on it!
      [You will find more information in the repo]
      Here's the link for the repo: https://github.com/giannismarinakis/java-open-nl
      Thanks!
    • By PaCkEtPiRaTe
      I'm currently remaking a game I made a few years back using Slick2D (as opposed to Swing/AWT, which was a terrible idea). I've fleshed out a lot of the background architecture, but I'm starting to run into issues with my architecture and I'm not sure how to proceed.
      The game I'm making is an overhead shooter. It's wave-based, with hordes of zombies coming at you. There are 10 weapons to choose from.
      Specifically, my latest issue is with a particular "weapon" I'm designing; the Laser Barrier. In the previous game, I had a "Laser Wire" weapon, which when two terminals were placed on the ground, created a wire made of laser on the ground that would damage enemies that passed through. Problem was that it didn't do enough damage in the short time that the enemies would be colliding with it for it to be of any use, so it was a waste of money.
      In the remake, I'm instead creating the "Laser Barrier", which visually looks the same, but instead of damaging enemies that touch it, it will act as an obstacle that enemies can't walk through. The enemies damage the shield while they are in contact with it until the laser barrier collapses. Projectiles however, can still pass through the barrier, allowing the player, and certain enemies, to shoot through them.
      The issue I'm running into, though, is the method of communicating between the Laser Wire itself and the enemy touching it. I'm currently able to detect a collision between the enemy and wire projected between the two laser terminals, but I'm not sure how I can implement the actual movement blocking part.
      It would take too much text to explain how it works, so here are the relevant files in my project:
      Player class - the checkProjectiles() method on line 344 is where the game loop checks for collisions between the player's weapon projectiles and the an enemy passed as an argument. On line 350, you can see that when there is a collision between the enemy and the LaserNode object (collision method is linked below), the laser node takes damage so that it will eventually be destroyed. I figured this is where the "movement blocking" should be, as I have access to the terminal and the enemy, and this is where a collision is confirmed. LaserNode class - this is the class representing the laser terminals on the ground that project the laser beam between them. The checkCollision() method on line 57 is used to determine if the enemy is touching either of the terminals, or if it is touching the beam itself. Enemy class - this is the base class for all game enemies. You can see what methods are available to all enemies, so perhaps this can provide some insight into what could be done to communicate with the LaserNode. I realize it's a lot to ask considering the scope of my project, but could someone give me an idea of how to communicate between the LaserNode and Enemy so that the enemy knows not to move when touching the LaserNode? The only methods I can think of seem cumbersome and it seems like I'd be adding a lot to the Enemy class just to get this one feature working.
      I'd love to script these weapons with LUA, but I never learned how to integrate a scripting language into my game architecture. I also have limited experience writing game engines, so I'm sure there's a lot of refinement that could be done to make my game architecture less restricting.
      I don't expect anyone to actually comb through my project and make suggestions, but I would super appreciate it.
    • By Oakman771
      Hello everybody     I am interested in learning how to develop an app/game for Android devices. I have experience with UE4 and know the basics of C++.  Would a very simple version of Armory & Machine be a good starter project? It should not contain physics or AI or similar. What would be the way to make something like that? I read a lot about Java related to Android on the internet.   Thanks for your help!
    • By Arnold577
      Hi there, 
      I have worked on multiple games in the past: text based/2D/3D.
      But now I want to make an mmo, specifically a text based one, known as a MUD.
      The thing is I don't know much about making them, I know:
      Loads of: C#, Python
      A bit of: HTML & JS
      Hardly any of: C++, Java
       
      What I would like to know is:
      How should I go about the networking? I know some sockets but don't like using others libraries.
      Is there any information on the topics that I haven't been able to find?
      And mainly, what language should I use. I am willing to learn a new one.
       
      THANK YOU IN ADVANCE
       
      I have done research.
       
    • By Juan Kang
      Hi everyone, 
      I've made a small java game recently, just for education purpose. So this game is a endless scrolling 2D plaformer. all you can do is jumping, with the impulse force to it. So the basic is to keep the player standing(and jumping) and move the background/platform from right to left. And with the forced jump, increase the force everytime the player press the button(e.g spacebar) and jump with the increased force when the button is released.
      Then,  I use Collision/Physics detection, with the platform in the air, or standing like a wall. So I want, when the player is hit against the wall, he will be dragged by it, as it move from right to left. And now I have 2 problems:
      - Sometime when the player is stand against a wall, and being dragged, he can't jump. Actually, just for a small distance and then stuck into a wall against him.

      - Some other times,  when I press/hold the button, he is going through the wall, and not even jump when I released the button.

      - The second problem is, when he falling, if he hit the platform, he got stuck to it, unable to jump anymore.


      I tried checking online for this, I believe I am probably Googling the wrong things to find tutorials for this, most tutorials seem to be for platformers like Rockman, or Flappy Bird,...But nothing seemed to solve my problems. 
      These are some of my code:
      Player.java
      package smithitsmiths; import bases.GameObject; import bases.Vector2D; import bases.inputs.InputManager; import bases.physics.BoxCollider; import bases.physics.Physics; import bases.renderers.ImageRenderer; import jdk.internal.util.xml.impl.Input; public class Player extends GameObject { private Vector2D velocity; private final float GRAVITY = 1f; private final float JUMPSPEED = 10; protected float force = 0; private BoxCollider boxCollider; final static int maxForce = 2; public static float currentForce; public GaugeBar gaugeBar; public Player() { super(); this.renderer = ImageRenderer.create("assets/images/players/player_walk1.png"); velocity = new Vector2D(); boxCollider = new BoxCollider(36, 45); this.children.add(boxCollider); gaugeBar = new GaugeBar(); GameObject.add(gaugeBar); } @Override public float run(Vector2D parentPosition) { super.run(parentPosition); //GRAVITY impact velocity && Inputs this.velocity.y += GRAVITY; if (InputManager.instance.spacePressed) { if (force <= maxForce) { gaugeBar.setValue(force); force += 0.1f; return currentForce = force; } } if (InputManager.instance.spaceReleased) { //when player is at platform(not in the air), enable jump, vice versa BoxCollider boxColliderAtBottom = this.boxCollider.shift(0, 1); if (Physics.collideWith(boxColliderAtBottom, Platform.class) != null) { velocity.y = -JUMPSPEED * force; } force = 0; gaugeBar.reset(); } //Platform physics moveVertical(); moveHorizontal(); //gaugebar update: gaugeBar.setPosition(this.position.x - 40, this.position.y - 40); return 0; } private void moveVertical() { //calculate future position(box collider) & predict collision BoxCollider nextBoxCollider = this.boxCollider.shift(0, velocity.y); Platform platform = Physics.collideWith(nextBoxCollider, Platform.class); if (platform != null) { //move player continously towards platform boolean moveContinue = true; float shiftDistance = Math.signum(velocity.y); while (moveContinue) { if (Physics.collideWith(this.boxCollider.shift(0, shiftDistance), Platform.class) != null) { moveContinue = false; } else { shiftDistance += Math.signum(velocity.y); this.position.addUp(0, Math.signum(velocity.y)); } } //update velocity () velocity.y = 0; } //velocity impact position this.position.addUp(0, velocity.y); this.screenPosition.addUp(0, velocity.y); } private void moveHorizontal() { //calculate future position(box collider) & predict collision BoxCollider nextBoxCollider = this.boxCollider.shift(velocity.x, 0); Platform platform = Physics.collideWith(nextBoxCollider, Platform.class); if (platform != null) { //move player continously towards platform boolean moveContinue = true; float shiftDistance = Math.signum(velocity.x); while (moveContinue) { if (Physics.collideWith(this.boxCollider.shift(shiftDistance, 0), Platform.class) != null) { moveContinue = false; this.position.subtractBy(platform.getSpeed(),0); } else { shiftDistance += Math.signum(velocity.x); this.position.addUp(Math.signum(velocity.x), 0); } } //end move player continously towards platform //update velocity () velocity.x = 0; } //velocity impact position this.position.addUp(velocity.x,0); this.screenPosition.addUp(velocity.x,0); } } Platform.java: package smithitsmiths; import bases.GameObject; import bases.Vector2D; import bases.physics.BoxCollider; import bases.physics.PhysicsBody; import bases.renderers.ImageRenderer; public class Platform extends GameObject implements PhysicsBody{ private BoxCollider boxCollider; private final float SPEED = 2; Vector2D velocity; public Platform() { super(); this.renderer = ImageRenderer.create("assets/images/platform/yellow_square.jpg"); boxCollider = new BoxCollider(30,30); this.children.add(boxCollider); velocity = new Vector2D(); } @Override public float run(Vector2D parentPosition) { super.run(parentPosition); velocity.x = -SPEED; position.addUp(velocity); return 0; } @Override public BoxCollider getBoxCollider() { return boxCollider; } public float getSpeed() { return SPEED; } }  
      BoxCollider.java:
      package bases.physics; import bases.GameObject; public class BoxCollider extends GameObject { private float width; private float height; public BoxCollider(float x, float y, float width, float height) { super(); this.position.set(x, y); this.screenPosition.set(x, y); this.width = width; this.height = height; } public BoxCollider(float width, float height) { this(0, 0, width, height); } public BoxCollider shift(float dx, float dy){ BoxCollider shiftedBoxCollider = new BoxCollider(this.width, this.height); shiftedBoxCollider.position.set(this.position.add(dx,dy)); //new position of newBC = current position + (dx,dy) shiftedBoxCollider.screenPosition.set(this.screenPosition.add(dx,dy)); return shiftedBoxCollider; } public float left() { return this.screenPosition.x - this.width / 2; } public float right() { return this.screenPosition.x + this.width / 2; } public float top() { return this.screenPosition.y - this.height / 2; } public float bottom() { return this.screenPosition.y + this.height / 2; } public float getWidth() { return width; } public float getHeight() { return height; } public boolean intersects(BoxCollider other) { return this.bottom() >= other.top() && this.top() <= other.bottom() && this.right() >= other.left() && this.left() <= other.right(); } @Override public String toString() { return "BoxCollider{" + "width=" + width + ", height=" + height + ", screenPosition=" + screenPosition + '}'; } }  
      So the ground is a total of many square platforms, with the BoxCollider of each. I really confuse where the bug is, and how to fix it. So I post it here hopefully you guys can tell me what to do. 
      I really appreciate it.

      Thanks for reading my post.
  • Popular Now