Programing

같은 클래스에있는 다른 개체의 개인 필드에 액세스

lottogame 2020. 10. 20. 07:11
반응형

같은 클래스에있는 다른 개체의 개인 필드에 액세스


class Person 
{
   private BankAccount account;

   Person(BankAccount account)
   {
      this.account = account;
   }

   public Person someMethod(Person person)
   {
     //Why accessing private field is possible?

     BankAccount a = person.account;
   }
}

디자인은 잊어주세요. 나는 OOP가 개인 객체가 클래스에 개인이라는 것을 지정한다는 것을 알고 있습니다. 내 질문은 왜 OOP가 개인 필드가 개체 수준 액세스가 아닌 클래스 수준 액세스를 갖도록 설계 되었습니까?


나는 또한 대답이 조금 궁금합니다.

내가 찾은 가장 만족스러운 대답은 여기 다른 게시물의 Artemix에서 가져온 것입니다 (AClass의 이름을 Person 클래스로 변경하고 있습니다). 왜 객체 수준 대신 클래스 수준 액세스 수정자가 있습니까?

private 한정자는 캡슐화 원칙을 적용합니다.

아이디어는 Person 구현이 시간이 지남에 따라 변경 될 수 있기 때문에 '외부 세계'가 Person 내부 프로세스를 변경해서는 안된다는 것입니다 (그리고 구현의 차이를 수정하기 위해 전체 외부 세계를 변경해야합니다-거의 불가능합니다).

Person의 인스턴스가 다른 Person 인스턴스의 내부에 액세스 할 때 두 인스턴스 모두 항상 Person의 구현 세부 정보를 알고 있는지 확인할 수 있습니다. 내부 프로세스의 로직이 변경되면 Person의 코드를 변경하기 만하면됩니다.

편집 : Artemix의 답변에 투표 하십시오 . 복사하여 붙여 넣는 중입니다.


Java 언어 사양, 섹션 6.6.1을 참조하십시오 . 접근성 결정

그것은 말한다

그렇지 않고 멤버 또는 생성자가 선언 된 경우 멤버 또는 생성자의 선언 private을 포함하는 최상위 클래스 (§7.6)의 본문 내에서 발생하는 경우에만 액세스가 허용됩니다.

자세한 내용은 위의 링크를 클릭하십시오. 그래서 대답은 다음과 같습니다. James Gosling과 다른 Java 작성자가 그렇게하기로 결정했기 때문입니다.


좋은 질문. 객체 수준 액세스 수정자는 캡슐화 원칙을 더욱 강화할 것으로 보입니다.

그러나 실제로는 그 반대입니다. 예를 들어 보겠습니다. 해당 개체의 전용 멤버에 액세스 할 수없는 경우 생성자에서 개체를 전체 복사하려고한다고 가정합니다. 그런 다음 가능한 유일한 방법은 모든 개인 구성원에 공용 접근자를 추가하는 것입니다. 이것은 당신의 개체를 만들 것 알몸 시스템의 모든 다른 부분.

따라서 캡슐화는 나머지 세계에 대해 폐쇄되는 것을 의미하지 않습니다. 그것은 당신이 누구에게 열려 있기를 원하는지에 대해 선택하는 것을 의미합니다.


이것은 당신이 class Person클래스 에 있기 때문에 작동합니다 -클래스는 자신의 클래스 유형 내부를 찌를 수 있습니다. 이것은 복사 생성자를 작성할 때 정말 도움이됩니다. 예를 들면 다음과 같습니다.

class A
{
   private:
      int x;
      int y;
   public:
      A(int a, int b) x(a), y(b) {}
      A(A a) { x = a.x; y = y.x; }
};

아니면 작성하려는 경우 operator+operator-우리의 큰 숫자 클래스.


때문에 private 액세스 한정자는 단지 내에서 그것을 볼 수 렌더링 클래스 . 이 메서드는 여전히 클래스에 있습니다.


private필드는 필드가 선언 된 클래스 / 객체에 액세스 할 수 있습니다. 위치가 아닌 다른 클래스 / 객체에 대해 비공개입니다.


Java의 리플렉션 개념을 사용하면 필드 및 메서드를 수정할 수 있습니다.

Modificando metodos y campos privados con Refleccion en Java


여기서 가장 먼저 이해해야 할 것은 우리가해야 할 일은 oops 원칙을 따라야한다는 것입니다. 그래서 캡슐화는 데이터를 패키지 (즉, 클래스) 안에 감싸고 모든 데이터를 Object로 표현하고 접근하기 쉽다는 것입니다. 따라서 필드를 개별적으로 액세스하는 것보다 비공개로 만들면. 나쁜 기생충이 생깁니다.


Java에서 비공개 가시성의 의미가 객체 수준이 아닌 클래스 수준 인 이유에 대한 질문에 대해 2 센트 만하겠습니다.

여기서는 편리함 이 핵심 이라고 생각 합니다 . 사실, 객체 수준의 비공개 가시성은 OP에 의해 설명 된 시나리오에서 다른 클래스 (예 : 동일한 패키지)에 메서드를 노출해야했습니다.

In truth I was not able neither to concoct nor to find an example showing that the visibility at class-private level (like offered by Java) creates any issues if compared to visibility at object-private level.

That said, programming languages with a more fine-grained system of visibility policies can afford both object visibility at object level and class level.

For example Eiffel, offers selective export: you can export any class feature to any class of your choice, from {NONE} (object-private) to {ANY} (the equivalent of public, and also the default), to {PERSON} (class-private, see the OP's example), to specific groups of classes {PERSON, BANK}.

It's also interesting to remark that in Eiffel you don't need to make an attribute private and write a getter to prevent other classes from assigning to it. Public attributes in Eiffel are by default accessible in read-only mode, so you don't need a getter just to return their value.

Of course you still need a setter to set an attribute, but you can hide it by defining it as "assigner" for that attribute. This allows you, if you wish, to use the more convenient assignment operator instead of the setter invocation.


Private in java is class level access as you wrote. Scala has also object private written as private[this] and other various ways detailed here http://alvinalexander.com/scala/how-to-control-scala-method-scope-object-private-package

Most probably private class level access in java was considered enough and is in sync with what c++ had at that moment.

I assume this was enough in java because a class was written in a single file so an author could decide to access members between different instances if it really wanted to. In scala you can inherit behavior from multiple traits and this might change the game.

참고URL : https://stackoverflow.com/questions/17027139/access-private-field-of-another-object-in-same-class

반응형