In his book, Test-Driven Development by Example, Kent Beck initially creates (in Java) a Dollar Object, then a Franc object using copy/paste inheritance to get to a green bar before removing the cut and paste duplication. When he subsequently refactors in order to eliminate the duplication, he creates a Money class from which both Dollar and Franc will derive. At some stage during this refactoring, the aim is to implement the public bool equals(Object object) in Franc in such a manner that it will become more generic and it would therefore be possible to
eliminate it in favor of the equals() in Money.
While doing so, the code:
public override bool Equals(object obj)
{
Franc franc = (Franc)obj;
return amount == franc.amount;
}
is changed to
public override bool Equals(object obj)
{
Money money = (Money) obj;
return amount == money.amount;
}
As the instance variable, "amount" is at this stage declared as Protected in Money,
the C# compiler error: "Cannot access protected member 'Namespace.BaseClass.Variable' via a qualifier of type 'NameSpace.BaseClass'; the qualifier must be of type 'NameSpace.InheritedClass' (or derived from it)" is generated.
The reason for this is:
"Although a derived
My workaround at this point is to simply skip the step where Money and Franc have their own implementation of equals() and go straight to where equals() resides in Money.
My question is: Do the implementations of the keyword Protected differ between C# and Java?
Many thanks!
J
J le RouxPosted Sep 8, 2007, 4:59 PM
I noticed that "protected internal" did the trick, but then I created a class, "widget", and, because it was in the same assembly, I could access the protected internal variable in Money. I guess one would be able to in Java too... Thanks again!
AlanPosted Sep 8, 2007, 8:38 AM
I would say that 'protected' in Java roughly corresponds to 'internal protected' in C#.
If something is marked as 'protected' in Java, then it can be accessed by any sub-class or by another class in the same package.
In C#, 'internal protected' means accessible by any sub-class or by any other type in the same assembly.
There's no real equivalent to C#'s 'protected' in Java unless, of course, the class containing the protected member is the only class in the package. IIRC, in early Java they used to have 'private protected' meaning accessible only by sub-classes but Sun got rid of it in later versions.
Possibly, in the example in the book, all the classes are defined in the same package as otherwise I don't see how you could access money.amount from the Franc class, even in Java.