views:

114

answers:

2

Hi
How can I prevent inheritance of some methods or properties in derived classes?!


public class BaseClass : Collection   
{  
    //Some operations...  
    //Should not let derived classes inherit 'Add' method.  
}

public class DerivedClass : BaseClass      
{        
    public void DoSomething(int Item)      
    {      
        this.Add(Item); // Error: No such method should exist...      
    }      
}  
+7  A: 

You can't, in this instance inheritance is the wrong tool for the job. Your class needs to have the collection as a private member, then you can expose as much or as little of it as you wish.

Binary Worrier
+8  A: 

The pattern you want is composition ("Has-a"), not inheritance ("Is-a"). BaseClass should contain a collection, not inherit from collection. BaseClass can then selectively choose what methods or properties to expose on its interface. Most of those may just be passthroughs that call the equivalent methods on the internal collection.

Marking things private in the child classes won't work, because anyone with a base type variable (Collection x = new DerivedClass()) will still be able to access the "hidden" members through the base type.

If "Is-a" vs "Has-a" doesn't click for you, think of it in terms of parents vs friends. You can't choose your parents and can't remove them from your DNA, but you can choose who you associate with.

dthorpe
+1: Love the "parents vs friends" metaphor :)
Binary Worrier