문제

나는 읽고있다 테스트 중심 개발 : 예에 따라 그리고 그 예 중 하나가 나를 괴롭 히고 있습니다. 3 장 (모두를위한 평등)에서 저자는 equals 기능 Dollar 둘을 비교하는 수업 Dollar 사물:

public boolean equals(Object object)
{
    Dollar dollar= (Dollar) object;
    return amount == dollar.amount;
}

그런 다음 다음 장에서 (4 : 개인 정보 보호), 그는 금액을 달러 클래스의 개인 구성원으로 만듭니다.

private int amount;

그리고 테스트가 통과됩니다. 이로 인해 컴파일러 오류가 발생하지 않아야합니다 equals 객체가 자체적으로 액세스 할 수 있기 때문에 방법 amount 회원은 다른 사람에 액세스하는 것이 제한되어 있습니다 Dollar 사물 amount 회원?

//shouldn't dollar.amount be no longer accessable?
return amount == dollar.amount

나는 근본적으로 오해하고 있습니다 private?

업데이트나는 책과 함께 수동으로 돌아가서 코딩하기로 결정했고, 다음 부분 (6 장 - 모든 사람을위한 평등, Redux)에 도착했을 때 부모 수업에 금액을 눌러 보호를받는 경우, 나는 액세스 문제를 받고 있습니다.

public class Money
{
    protected int amount;
}

public class Dollar : Money
{
    public Dollar(int amount)
    {
        this.amount = amount;
    }
    // override object.Equals
    public override bool Equals(object obj)
    {
        Money dollar = (Money)obj;
        //"error CS1540: Cannot access protected member 'Money.amount'
        // via a qualifier of type 'Money'; the qualifier must be of 
        // type 'Dollar' (or derived from it)" on the next line:
        return amount == dollar.amount;
    }
}

이것은 그것을 의미합니까? protected 인스턴스 기반은 C#입니까?

도움이 되었습니까?

해결책

Yep, you're fundamentally misunderstanding private. Privacy is class-specific, not instance-specific.

다른 팁

Fundamentally misunderstanding private, Dollar can access any Dollar private method if they are the same class.

Modifier private is class-private, not object-private.

In Java, private means class-private. Within the class, you can access that field in all instances of the class.

In Scala there is also an object-private scope which is written private[this]. Also in other respects Scala's scopes are more flexible (see this article for more information).

But in Java there is no object-private scope.

In languages of the C++ family (C++,Java,C#), access control is only at the class level. So private allows access to any instance of that class.

IIRC in Smalltalk privacy behaves as you expect.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top