-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.

2

2 Answers 2

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;
}
2
  • 1
    I don't think that counts as "direct" though Commented Feb 12, 2016 at 3:17
  • 1
    @BenjaminLowry it's the closest thing in the Java language to what the OP wants. Commented Feb 12, 2016 at 3:17
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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.