J le Roux

J le Roux

  • NA
  • 3
  • 0

Meaning of "Protected" in C# vs Java?

Sep 8 2007 2:59 AM
Hi All,

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 class can access protected members of its base class, it cannot do so through an instance of the base class."

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

Answers (2)