Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent inheritance for some methods?

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...      
    }      
}  
like image 403
Dr TJ Avatar asked Sep 22 '10 18:09

Dr TJ


1 Answers

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.

like image 164
dthorpe Avatar answered Oct 06 '22 00:10

dthorpe