java) Can private access restrictors be accessed through return?

Asked 2 years ago, Updated 2 years ago, 115 views

class A {
  private String name;

  public void getName() {
    return name;
  }
}

If this class exists, the member name is set to private

Private can only be accessed within the class, right?

However, if you return the name to a method declared as public, such as getName(),

There was no error.

Then, if we change the value in the returned instance, doesn't the value of the name also change?

Because String is also a class, so if you initialize the name, it becomes an instance

If you return it, it returns a string address, not a simple string, so

The returned instance will point to the same address as the name.

So I think if you change the value in the instance, the value of the name will also change.

In this case, I thought what does private mean?

In terms of restricting simple direct access, I understand that private use is the stability of the code?B

I heard it's going to be high, but I think it would be meaningful if I could return it and access it like this.

Is it supposed to be like this?

java private

2022-09-20 17:27

1 Answers

when asked about the benefits of using getter isin?

Using getter is the programmer's choice. However, the problem you mentioned as an example is inevitable if you don't use getter, but if you use getter, you can avoid it by returning clone or disclosing only some properties of member variables. Subsequent changes in member variables can also isolate the influence within the class. It would be helpful to learn about Open-Closure Principle.


2022-09-20 17:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.