简体   繁体   中英

How to set a new value for a public int in java

In the java programming language, how do you set a new value for a public integer, so that an outside method in an outside class can get this value, by simply calling the variable name. I have example code:

    package build;

    public class Main {

        public static void main(String[] args) {
            Main main = new Main();
            main.init();
        }

        public int myVar = 1;

EDIT:

More specific question: How can I get the variable's updated value, not it's starting value without passing it on to a the method?

        public void init() {
            Retrieve ret = new Retrieve();
            int i = 0;
            for(int n = 1; n > 0; ++n) {
                myVar = myVar + 1;
                System.out.println("Value: " + myVar);
                i = ret.init();
                System.out.println("Retrieved Value: " + i);
            }
        }

        int getValue()  {
            int b = myVar;
            return b;
        }
    }

and for Return:

    package build;

    public class Retrieve {

        public int init() {
            Main main = new Main();
            int a = 1;
            a = main.getValue();
            return a;
        }
    }

In the example above, how would I set the variable "myVar" to a value other than one, so that when I call the 'init' method in the 'return' class, it returns that new value, rather than 1, the starting value?

There's something very wrong with your object relationship.

The main problem is in Retrieve.init()

public int init() {
        Main main = new Main();
        int a = 1;
        a = main.getValue();

Every time you call init() you are making a new instance of main, so main.myVar will be 1. I assume you wanted to call the value of the first main.

public class Retrieve {

    public int init(Main main) {            
        int a = 1;
        a = main.getValue();
        return a;
    }
}

and in Main.init change

Retrieve ret = new Retrieve();

to

Retrieve ret = new Retrieve(this);

It's fairly awful OOP , but this will work:

public class Retrieve {

    public int init() {
        Main main = new Main();
        int a = 1;
        main.myVar = 42;
        a = main.getValue();
        return a; // returns 42
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM