简体   繁体   中英

Changing private fields in Java using public methods

In C++ there is a way to change data even if it's private:

class Foo
{
private:
    char * i;
public:
    char * getInt() {return i;};
    Foo() {i="Winter";};
}

int main()
{
  Foo a;
  strcpy(a.getInt(), "Summer"); //it changes i
  cout<<a.getInt(); //gives "Summer"

  return 0;
}

Is there some way to do that in Java?

EDIT: If there is, then is there some keyword like const in C++, to prevent such behaviour?

Java returns copies of pointers to objects (and copies of the value of primitives). A String is such an object. Eg

class Foo {
    private String i = "Winter";
    public String get() { return i; }
}

Now that is perfectly safe and nothing (except reflection) can change your private field or it's state:

void main() {
  Foo a = new Foo();
  String i = a.get();
  String j = i + " rocks"; // creates a new string
  i = "Summer"; // now points to another string
  System.out.println(a.get()); // still prints "Winter"
}

However, if code is able to modify the returned object, you can't prevent that it changes it.

Java also has no builtin way to make objects immutable, you must design them to be effectively immutable, like the String class for example. Every method that "modifies" a string actually creates a new immutable string that can be shared among all places & threads without worries.

If your class was

class Foo {
    public String i = "Winter";
}

you wouldn't be safe. Code could change what that field points to.

void main() {
  Foo a = new Foo();
  a.i = "Summer"; // that works.
  System.out.println(a.i); // prints "Summer"
}

While you shouldn't have public fields especially if you don't want it to be modified, there is something that helps: final .

class Foo {
    public final String i = "Winter";
}
void main() {
  Foo a = new Foo();
  a.i = "Summer"; // Error: final field cannot be modified.
}

The final keyword guarantees that a field is assigned exactly once. The field needs to have a value after the constructor finishes, and it cannot be changed afterwards. The referenced object however may still be mutable, merely the reference to it isn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM