简体   繁体   中英

How do you transfer a variable defined in the main method of one class to another?

I have seen this done in many programs but I cant seem to follow the programming logic.

Lets say you have a simple class, ClassB. And in ClassB's main method you define an integer variable:

public class B {
    public static void main(String[] args) {
        int stuff = 333;
    }
}

How can you transfer the variable to a different class, say ClassA, to be used.

public class A {
    public static void main(String[] args) {    
        System.out.println(stuff);
    }
}

Can someone please explain this to me in simple terms. I've been trying to learn this for 2 hours and cant wrap my head around it.

You shouldn't have 2 main methods. Only one class should (typically):

ClassA.java

public class A {
    public static void main(String[] args) {
        ClassB b = new ClassB();
        System.out.println(b.stuff);
    }
}

ClassB.java

public class B {
    public int stuff = 333; // member variable
}

You instantiate the second class in the first one, then you're granted access to its public member variables .

public static void main(String[] args) is meant to be used as a starting point for a Java program. Probably it's better to rename one of your methods to something else.

The problem you are seeing, is that the scope of the variable int stuff is limited to the main() method of class B , because it is declared within the body of the main() method. In order to make it visible, you need to declare it as a public field (which can be static in your case).

I propose you change your program like follows:

public class A {

    public static int stuff;

    public static void initStaticMembers() {
        stuff = 333;
    }

}
public class B {

    public static void main(String[] args) {

        A.initStaticMembers();

        System.out.println(A.stuff);

    }

}

I renamed the main() method of A to initStaticMembers() and dropped the method parameters, since they are not needed in our case. In order to use the field A.stuff in B , the method A.initStaticMembers() needs to be called first.

Of course there are ways to improve this program, but I think you should learn Java one step at a time.

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