variable seen by all classes Java

Refresh

6 days ago

Views

12.1k time

1

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

0

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.

4

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;
              //^^^^^^^
    }
}