views:

862

answers:

4

I have four classes which share some arrangement of four properties. I have currently set the base class to be abstract with each property marked as virtual. Then in each of the four derived classes I am overriding the properties which it uses and ignoring the others.

The problem is that I can still access all properties in each of the derived classes, regardless of whether I have overriden it from the abstract virtual property in my base class.

I have a feeling that I am approaching this from the wrong angle. Is there a way to explicitly hide or block properties, or is there a better approach.

+1  A: 

I'm afraid it's not possible to hide members in a derived class .(that's against the inheritance rules) To solve this problem you can have two level of abstract classes.In level one there's a base class with all the members that should be among all the derived classes , in second level you can have special classes with only the members you want to be inherited from this class down.

//Level1
public abstract class Employee
{
public string Name{get;set;}
public abstract double CalculateSalary();

}

//Level2
public abstract class CalssAEmployee:Employee
{
public int NumberOfWorkingHours{get;set;}

}

public abstract class ClassBEmployee:Employee
{
public int NumberOfSales{get;set;}
}
Beatles1692
+7  A: 

I believe you should rethink your inheritance hierarchy. Consider the following heuristics:

If two or more classes share only common data (no common behavior), then that common data should be placed in a class that will be contained by each sharing class.

If two or more classes have common data and behavior (i.e., methods), then those classes should each inherit from a common base class that captures those data and methods.

If two or more classes share only a common interface (i.e., messages, not methods), then they should inherit from a common base class only if they will be used polymorphically.

Dzmitry Huba
A: 

There are a couple of rules in play here.

if you have an abstract class, with virtual properties, they can either be protected or public and this is what the outside world will see. When you extend/inherit this class, you can override these properties but not mark them as private. Private is the only way to hide a property from the derived class. Having a private property in abstract class will hide it from the children. But that is obviously not the case in your scenario.

Zaki
+1  A: 

You cannot remove/hide methods or properties in derived classes as this contradicts liskov's substitution principle.

You can override the properties to throw Exceptions but this is no good Design.

You should have in a class only the members which are actually valid on this class.

Maybe you want to define several interfaces having your properties and let each class implement the interfaces you need.

codymanix
Yeah, that is the approach I was thinking of as I wrote this question. Thanks for the clarification.
JMs