Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define Global variable outside class?

Tags:

java

I'd like to define variable which can share values to classes.

so I tried as following.

But It occured error.

How to share a value to classes?

package com.company;

    /////// Error occurred ///////
    int sharedValue = 100;   // <- How to share to classes?
    //////////////////////////////

    public class Main {

        public static void main(String[] args) {
            sharedValue += 10;

            GlobalTest globalTest = new GlobalTest();
            globalTest.printGlobalValue();
        }
    }

    class GlobalTest {
        void printGlobalValue() {
            System.out.println(sharedValue);
        }
    } 
like image 364
S.J. Lim Avatar asked May 09 '26 05:05

S.J. Lim


2 Answers

You can declare it as a static value in your class:

public class Main {
    public static int sharedValue = 100;
    ....
}  

and access it from other classes using:

Main.sharedValue
like image 118
Kara Avatar answered May 11 '26 17:05

Kara


use static in a class instead

public class Blah {
    public static int a = 100;
}

can be accessed by Blah.a

like image 34
Kevin Avatar answered May 11 '26 17:05

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!