Reputation: 221
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?
Upvotes: 4
Views: 21014
Reputation: 137392
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;
//^^^^^^^
}
}
Upvotes: 7
Reputation: 8874
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.
Upvotes: 0