Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable seen by all classes Java

Tags:

java

I'm a beginner in java, so I don't know if there is any way to make a variable seen by all classes in same package?

like image 429
Samiah Avatar asked Oct 20 '25 16:10

Samiah


1 Answers

The default modifier (just don't write public/private/protected) gives access from inside the package only. (Take a look here)

But as a rule, it is a good practice to avoid accessing variables directly.

Edit:

Responding the comments, if you want to access this variable without creating an object, then it should be static:

package com.some.package;
public class MyClass {
    static int someInt = 1;
}

Then to access it, you need to qualify it by the class:

package com.some.package;
public class AnotherClass {
    public void someMethod() {
        int i = MyClass.someInt;
              //^^^^^^^
    }
}
like image 193
MByD Avatar answered Oct 23 '25 06:10

MByD