I'm reading through Test Driven Development: By Example and one of the examples is bugging me. In chapter 3 (Equality for all), the author creates an equals
function in the Dollar
class to compare two Dollar
objects:
public boolean equals(Object object)
{
Dollar dollar= (Dollar) object;
return amount == dollar.amount;
}
Then, in the following chapter (4: Privacy), he makes amount a private member of the dollar class.
private int amount;
and the tests pass. Shouldn't this cause a compiler error in the equals
method because while the object can access its own amount
member as it is restricted from accessing the other Dollar
object's amount
member?
//shouldn't dollar.amount be no longer accessable?
return amount == dollar.amount
Am I fundamentally misunderstanding private
?
UPDATE I decided to go back and code along with the book manually and when I got to the next part (chapter 6 - Equality For All, Redux) where they push amount into a parent class and make it protected, I'm getting access problems:
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;
}
}
Does this mean that protected
IS instance-based in C#?
Yep, you're fundamentally misunderstanding private. Privacy is class-specific, not instance-specific.
从根本上误解私人,如果他们是同一个班级,美元可以访问任何美元私人方法。
修饰符private是class-private ,而不是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.
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.