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?
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;
//^^^^^^^
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With