In java, is there a (direct) way to make a variable able to be accessed out of the class but not able to be changed? I have a variable in class A and need it in class B. I can make it public (bad-practice) but i don't want class B to be able to change it. Is there a way to do this or will I just have to make it public and be careful? Also I need to maintain the ability to change the variable from within Class A, ruling out final.
2 Answers
Yes: you can provide a getter. That's pretty much it, but that's how you're supposed to do it.
public Type getField() {
return field;
}
-
1
-
1@BenjaminLowry it's the closest thing in the Java language to what the OP wants. Commented Feb 12, 2016 at 3:17
you can use reflection to read the private values.
public class Test1 {
private int num;
public Test1(int n){
this.num =n;
}
}
Accessing private variable
Field classField = Test1.class.
getDeclaredField("num");
classField.setAccessible(true);
classField.getInt(t);
System.out.println(classField.getInt(t));