variable seen by all classes Java


February 2019


12.3k time


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?

2 answers


static <type> <variable name>;

If you do not supply access modifier, it defaults to package-private. It means that the variable is visible only to members of the same package.


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.


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;