-2

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.

Jean Valjean
  • 747
  • 1
  • 9
  • 30
  • Please refer, http://stackoverflow.com/questions/14324805/class-variable-public-access-read-only-but-private-access-r-w – Prabhakar Feb 12 '16 at 03:58
  • http://stackoverflow.com/questions/8151342/do-we-have-a-readonly-field-in-java-which-is-set-able-within-the-scope-of-the-c http://stackoverflow.com/questions/14324805/class-variable-public-access-read-only-but-private-access-r-w – Prabhakar Feb 12 '16 at 04:00

2 Answers2

2

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;
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

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));
Sarabala
  • 354
  • 1
  • 3
  • 7