I hope this isn't a duplicate but I can't find one via Google or SO search. If I want to force the accessibility for a method's implementation of an overridden method to be protected, is my only option to either create as abstract or protected virtual? I know that interfaces specify the declaration but leave the accessibility/scope to the class implementation but I'd like to be sure.
I'd like to know/be certain of if the only way to limit the scope of a method is via a abstract \ protected virtual to give semantics of "this applies to the class implementation or the child override implementation".
A code sample to illustrate. I know I can do the following and limit the scope of an implementation like so;
public class BaseClass
{
protected virtual void OnlyMeOrChildrenCanDoAction()
{
// leave empty as current class is structural/conceptual
// but child instances may need it
}
}
By doing the above I guarantee that child implementations can only override OnlyMeorChildrenCanDoAction()as protected but not public.
But is there another way of limiting to protected without resorting to abstract or protected virtual? An example of creating a method like this is Object.Finalize() as seen here.
Or, to invert the question somewhat, why would you create a method as protected virtual unless to ensure that any implementations were limited in scope? Or is there another way to do the same?
I think you're misunderstanding the meaning and use of virtual. You can only override a method in the parent class if it is declared virtual. The override method in the child class must have the same visibility as the method in the parent class.
Implementations of methods declared in interfaces are always public.
Declaring a method abstract has the same effect as declaring it virtual, except you do not implement it in your class and any concrete classes that derive from your class must implement it.
Technically, the compiler will not allow you to change the access modifiers of a method when overriding it from the parent, so the answer to the question is that by declaring a method as protected within a class, you are only making it available to derived classes (whether abstract or not is a separate concern and doesn't bear on the access level).
Keep in mind, however, that derived class would be free to expose the function in some other way such as calling the protected method from a public one and there is no way to prevent that.
As far as "why" you would have a protected abstract member, a great example can be seen in many implementations of the Template Method pattern. You may have an abstract base class that describes the structure of an algorithm and leave the specific steps of what happens inside the boundary of each step to derived classes. In this case, one way to implement would be to declare the base class as abstract, have a public method serve as the "entry point" for the algorithm, and define specific methods used within the algorithm as protected abstract methods to lay out what the responsibility of derived classes will be. This pattern does a nice job of leaving public only those things that are intended to be consumed by the world, but can present some challenges from a unit testing perspective which are sometimes addressed by raising the visibility of the helper methods from protected to internal.
You cannot use the c# language to prevent a derived class from implementing a public version of OnlyMeOrChildrenCanDoAction. Even if you mark it as protected virtual, the derived class can use the new keyword to cover the method and change its accessibility. For example:
public class BaseClass
{
protected virtual void OnlyMeOrChildrenCanDoAction()
{
// leave empty as current class is structural/conceptual
// but child instances may need it
}
}
public class DerivedClass : BaseClass
{
public new void OnlyMeOrChildrenCanDoAction()
{
Console.WriteLine("This is public.");
}
}
public class Program
{
public static void Main()
{
var b = new BaseClass();
//b.OnlyMeOrChildrenCanDoAction(); //Will not compile
var d = new DerivedClass();
d.OnlyMeOrChildrenCanDoAction(); //Look! It's public!
}
}
Output:
This is public.
Code available on DotNetFiddle.
If you want to protect the caller from calling OnlyMeOrChildrenCanDoAction, your best bet is for the caller to use only interfaces. If OnlyMeOrChildrenCanDoAction isn't in the interface, there is no way a caller could call it, even if a derived class decided to expose it as a public class member. This is good SOLID design anyway.
On the other hand, if you're not so much worried about the caller as you are worried about your own development team doing bad things, perhaps your best option is to use FxCop or some other source code rules engine integrated into your continuous build process. Developers could still add the method but you could set up a rule to cause it to fail the build if they do so.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a class A which derives from class B:
public class B
{
protected void Run() // pass data here used by all 3 Run methods
{
BeforeRun();
RunInternal();
AfterRun();
}
private void RunInternal()
{
}
private void BeforeRun()
{
}
private void AfterRun()
{
}
}
public class A : B
{
}
What is the nearest achievement I can get to force the user who inherits from class B MUST call the base method Run() ?
Add protected, virtual, abstract, etc... where you want, I am free to do changes where you suggest.
You can't require someone to call a method, except for the constructor. But a class's behavior shouldn't be in the constructor or called from the constructor. A class shouldn't start doing something just because we instantiated it. It should do something when we call its methods.
When we design a class it typically has one or two methods which are the primary responsibility of that class. Whoever creates an instance of the class is going to call one or more of those methods because that's the only reason why the class exists.
Instead of adding another method and expecting others to call it, you design the class so that the primary methods cannot be overridden. The only public methods are in the base class. The methods that get overridden aren't public. That way the base class methods always get called, and if there's something you want the base class to always do, it always gets done.
That way other classes don't change the required base class behavior. They only extend it.
public abstract class TheBaseClass
{
public void DoSomething()
{
AlwaysDoThis();
InheritedClassBehavior();
}
private void AlwaysDoThis()
{
//This method in the base class always gets called.
//You don't need to explicitly require someone
//to call it.
}
protected abstract void InheritedClassBehavior();
}
public class TheInheritedClass : TheBaseClass
{
protected override void InheritedClassBehavior()
{
//The inherited class has its own behavior here.
//But this method can't be called directly because
//it's protected. Someone still has to call
//DoSomething() in the base class, so AlwaysDoThis()
//is always called.
}
}
InheritedClassBehavior is protected, so nothing can call it directly. The only way to call it is by calling DoSomething, which will always call the method in the base class, AlwaysDoThis().
InheritedClassBehavior is abstract, so inherited classes must implement it. Or you could make it virtual - it has an implementation in the base class but an inherited class can override it. (If there aren't any abstract methods then the base class doesn't need to be abstract. The base class would only be abstract if you want to prevent creating instances of the base class, only allowing creation of inherited classes.)
Your best option is to have a base implementation in A (so make it virtual), and only override it in the derived classes if they need to change the behavior of Run().
Anything that calls Run() will get the base implementation unless there has been an override supplied. There is no way you can force the override to call the base, classical OO simply doesn't work like that.
You should also be careful of calling a virtual method from a constructor - Resharper will warn you about this (because an override may get called, and this is unknown to the base implementation).
But other than that, there is no way within C# to force a derived class to call a particular method - a derived class extends the base class, so to force this sort of behavior would break basic OO concepts. Even if you put the calls into a constructor in the base class there is no guarantee that a derived class will invoke that constructor. You can force the base class to call the derived class (use an abstract base method, this must be implemented in the derived class), the derived method can then call back to a base method; but this in itself is a bit of a work around that is really a waste of time unless some of the derived classes are actually going to add some functionality to Run().
One other approach to consider is to use a product like PostSharp - it allows you to use attributes on methods to achieve a cross cutting pattern. This still doesn't force a derived class to call base implementations, but it may be a convenient way to achieve what you are wanting (cross cutting is used for auditing or logging patterns, where a specific method must be called when another method is invoked).
I want to know the reason behind the design of restricting Abstract Methods in Non Abstract Class (in C#).
I understand that the class instance won't have the definition and thus they wont be callable, but when static methods are defined,they are excluded from the instance too. Why abstract methods are not handled that way, any specific reason for the same?
They could be allowed in concrete class and the deriving class can be forced to implement methods, basically that is what, is done in case of abstract methods in an abstract class.
First, I think that what you're asking doesn't logically make sense. If you have an abstract method, it basically means that the method is unfinished (as #ChrisSinclair pointed out). But that also means the whole class is unfinished, so it also has to be abstract.
Or another way to put it: if you had an abstract method on a class that wasn't abstract, that would mean you had a method that cannot be called. But that means the method is not useful, you could remove it and it would all work the same.
Now, I'll try to be more concrete by using an example: imagine the following code:
Animal[] zoo = new Animal[] { new Monkey(), new Fish(), new Animal() };
foreach (Animal animal in zoo)
animal.MakeSound();
Here, Animal is the non-abstract base class (which is why I can put it directly into the array), Monkey and Fish are derived from Animal and MakeSound() is the abstract method. What should this code do? You didn't state that clearly, but I can imagine few options:
You can't call MakeSound() on a variable typed as Animal, you can call it only using a variable typed as one of the derived classes, so this is a compile error.
This is not a good solution, because the whole point of abstract is to be able to treat instances of derived classes as the base class, and still get behaviour that's specific to the derived class. If you want this, just put a normal (no abstract, virtual or override) method into each derived class and don't do anything with the base class.
You can't call MakeSound() on an object whose runtime type is actually Animal, so this is a runtime error (an exception).
This is also not a good solution. C# is a statically typed language and so it tries to catch errors like “you can't call this method” at compile time (with obvious exceptions like reflection and dynamic), so making this into a runtime error wouldn't fit with the rest of the language. Besides, you can do this easily by creating a virtual method in the base class that throws an exception.
To sum up, you want something that doesn't make much sense, and smells of bad design (a base class that behaves differently than its derived classes) and can be worked around quite easily. These are all signs of a feature that should not be implemented.
So, you want to allow
class C { abstract void M(); }
to compile. Suppose it did. What do you then want to happen when someone does
new C().M();
? You want an execution-time error? Well, in general C# prefers compile-time errors to execution-time errors. If you don't like that philosophy, there are other languages available...
I think you've answered your own question, an abstract method isn't defined initially. Therefore the class cannot be instanciated. You're saying it should ignore it, but by definition when adding an abstract method you're saying "every class created from this must implement this {abstract method}" hence the class where you define the abstract class must also be abstract because the abstract method is still undefined at that point.
The abstract class may contain abstract member. There is the only method declaration if any method has an abstract keyword we can't implement in the same class. So the abstract class is incompleted. That is why the object is not created for an abstract class.
Non-abstract class can't contain abstract member.
Example:
namespace InterviewPreparation
{
public abstract class baseclass
{
public abstract void method1(); //abstract method
public abstract void method2(); //abstract method
public void method3() { } //Non- abstract method----->It is necessary to implement here.
}
class childclass : baseclass
{
public override void method1() { }
public override void method2() { }
}
public class Program //Non Abstract Class
{
public static void Main()
{
baseclass b = new childclass(); //create instance
b.method1();
b.method2();
b.method3();
}
}
}
You can achieve what you want using "virtual" methods but using virtual methods can lead to more runtime business logic errors as a developer is not "forced" to implement the logic in the child class.
I think there's a valid point here. An abstract method is the perfect solution as it would "enforce" the requirement of defining the method body in children.
I have come across many many situations where the parent class had to (or it would be more efficient to) implement some logic but "Only" children could implement rest of the logic"
So if the opportunity was there I would happily mix abstract methods with complete methods.
#AakashM, I appreciate C# prefers compile time errors. So do I. And so does anybody. This is about thinking out-of-the-box.
And supporting this will not affect that.
Let's think out of the box here, rather than saying "hurrah" to big boy decisions.
C# compiler can detect and deny someone of using an abstract class directly because it uses the "abstract" keyword.
C# also knows to force any child class to implement any abstract methods. How? because of the use of the "abstract" keyword.
This is pretty simple to understand to anyone who has studied the internals of a programming language.
So, why can't C# detect an "abstract" keyword next to a method in a normal class and handle it at the COMPILE TIME.
The reason is it takes "reworking" and the effort is not worth supporting the small demand.
Specially in an industry that lacks people who think out of the boxes that big boys have given them.
It's still not clear why you would want that, but an alternative approach could be to force derived classes to provide a delegate instance. Something like this
class MyConcreteClass
{
readonly Func<int, DateTime, string> methodImpl;
// constructor requires a delegate instance
public MyConcreteClass(Func<int, DateTime, string> methodImpl)
{
if (methodImpl == null)
throw new ArgumentNullException();
this.methodImpl = methodImpl;
}
...
}
(The signature string MethodImpl(int, DateTime) is just an example, of course.)
Otherwise, I can recommend the other answers to explain why your wish probably isn't something which would make the world better.
So the answers above are correct: having abstract methods makes the class inherently abstract. If you cannot instance part of a class, then you cannot instance the class itself. However, the answers above didn't really discuss your options here.
First, this is mainly an issue for public static methods. If the methods aren't intended to be public, then you could have protected non-abstract methods, which are allowed in an abstract class declaration. So, you could just move these static methods to a separate static class without much issue.
As an alternative, you could keep those methods in the class, but then instead of having abstract methods, declare an interface. Essentially, you have a multiple-inheritance problem as you want the derived class to inherit from two conceptually different objects: a non-abstract parent with public static members, and an abstract parent with abstract methods. Unlike some other frameworks, C# does permit multiple inheritance. Instead, C# offers a formal interface declaration that is intended to fill this purpose. Moreover, the whole point of abstract methods, really, is just to impose a certain conceptual interface.
I have a scenario very similar to what the OP is trying to achieve. In my case the method that I want to make abstract would be a protected method and would only be known to the base class. So the "new C().M();" does not apply because the method in question is not public. I want to be able to instantiate and call public methods on the base class (therefore it needs to be non-abstract), but I need these public methods to call a protected implementation of the protected method in the child class and have no default implementation in the parent. In a manner of speaking, I need to force descendants to override the method. I don't know what the child class is at compile time due to dependency injection.
My solution was to follow the rules and use a concrete base class and a virtual protected method. For the default implementation, though, I throw a NotImplementedException with the error "The implementation for method name must be provided in the implementation of the child class."
protected virtual void MyProtectedMethod()
{
throw new NotImplementedException("The implementation for MyProtectedMethod must be provided in the implementation of the child class.");
}
In this way a default implementation can never be used and implementers of descendant implementations will quickly see that they missed an important step.
If I have a project that contains similar classes and some may use the same implementation, but in most cases they implement their own way of handling the methods defined in an interface or abstract class. I am trying to figure out if an interface/abstract class is better or not. I don't get the point of an interface if you can just use an abstract class with virtual abstract methods.
Here is an interface:
public interface IAthlete
{
void Run();
}
Here is an abstract class:
public abstract class Athlete
{
public abstract void Run();
}
Here is an implementation of the interface:
public class Sprinter : IAthlete
{
public void Run()
{
Console.WriteLine("Running Fast....");
}
}
Here is an extension of the abstract class:
public class MarathonRunner : Athlete
{
public override void Run()
{
Console.Write("Jogging....");
}
}
Now if I decide to add a method called Stop to either the interface or abstract method, Sprinter and MarathonRunner both break and because I can provide some default implementation to abstract, it seems like a better choice. Am I missing something?
There are 2 main differences between Interfaces and abstract super-classes:
Abstract Classes
code reuse is possible by using an abstract super-class
you can only inherit one super-class
Interfaces
every method has to be implemented in each sub-class
a class can inherit more than 1 interface (multiple inheritance)
In the case where all you have is one piece of commonality to extract, you're quite right that there isn't a substantive difference between the two. But this is rather like saying "in the case of adding 1 to 2, there's no difference between an int and a double" - it's technically true, but not a particularly useful guide to how to think.
In case with any more complexity than this (that is, in most cases) there will be more classes, and pieces of common baheaviour to extract. Then you have to start making a significant choice between class inheritance and interface implementation, taking into account things like:
you only get one shot at choosing a base class, but you can implement as many interfaces as you like
if you want your 'parent' to do any work, it needs to be a class not an interface
and so on.
In general, the semantics of your classes should guide you - where the 'things' have an "IS A" relationship (like MarathonRunner to Athlete), inheritance is suggested; where the 'things' have an "I CAN FULFIL THE CONTRACT OF A" (like, say, Person to Runner), interface implementation is suggested.
Interfaces are a btter way to go as the current consensus amongst the .NET developer comunity is that you should favour composition over inheritance, so Interfaces are a much better strategy (think of Injection Containers and how usefull they are as well, and lets not get started on unit testing).
also, classes can implement many interfaces but can only inherit from one class (abstract or otherwise). also structs can implement interfaces but not inherit from another class.
At the runtime level, interfaces are more efficient as the runtime doesnt have to walk the inheritance stack in order to work out the polymorphic implications of calling a specific member.
Interfaces are a very useful feature, and are very similar to abstract classes, and in some circumstances, exchangable with abstract classes.
But, don't jump straight to interfaces, unleass you have to (very common antipattern in Java developers). I suggest, by reading your example, to stick to abstract classes.
Most of the times I only use interfaces, when I have several non related classes, and I need them to have common members, as If these classes came from the same base class.
In your example, you are trying to find what happen if you need a new stop method, when adding a base virtual method. These can be solved in a different approach, that is not Abstract Classes versus interfaces.
There are 3 choices:
(1) Add an abstract method that coerce the programmer to override it, in order to instantiate objects.
(2) Add a new virtual method that does something, but doesn't have to be overriden.
(3) Add a new method that does nothing, maybe applies to your case.
// cannot instantiate an abstract class
public abstract class Athlete
{
// helper method:
public /* non-abstract */ void DoNothing()
{
// does nothing on purpouse !!!
}
// (1) virtual & abstract method, must be overriden
public abstract void Run();
// (2) new virtual method, doesn't need to be overriden,
// but, maybe you dont like what it does
public virtual void Stop()
{
Message.Show("Stop !!!");
}
// (3) new virtual method, doesn't need to be overriden,
// its safe to be called
public virtual void TakeBreak()
{
// works like an abstract virtual method, but, you don't need to override
DoNothing();
}
} // class Athlete
// in a non abstract class, you must override all abstract methods
public /* non-abstract */ class Runner: Athlete
{
public override void Run()
{
DoNothing();
}
public override void Stop()
{
DoNothing();
}
// don't need to override this method
// public virtual void TakeBreak();
} // class Trekker
// ...
Runner ARunner = new Runner();
ARunner.Run();
ARunner.Stop();
ARunner.TakeBreak();
The third kind of virtual method, that may apply to your example, doesnt' have a special name, I already post a question about it on stackoverflow, but, nobody knew an special name for this case.
Cheers.
An important difference between interfaces and abstract classes is how their members handle multi-generational inheritance. Suppose there's an abstract class BaseFoo with abstract method Bar and interface IFoo with method Boz; class Foo inherits BaseFoo and implements IFoo, and class DerivedFoo inherits from Foo.
If DerivedFoo needs to override BaseFoo.Bar, it may do so, and its override may call base.Bar() if it needs to use its parent's implementation. If Foo implements Boz implicitly using a virtual method, then DerivedFoo may override that method and call base.Boz() (the override being a function of the class rather than the interface) but if Foo explicitly implements IFoo.Boz, then the only way for DerivedFoo to change the behavior of IFoo.Boz will be to re-implement it. If it does so, then Foo's implementation of IFoo.Boz will become inaccessible, even within DerivedFoo's implementation of the same interface member.
Whenever i override a method of a base class, other than my implementation of this method, i seem to have 3 choices.
1) Call base.Method(), and then provide my implementation.
2) Provide my implementation and then call base.Method()
3) Just provide my implementation.
Recently while using a library i have realized few bugs that were introduced because of not implementing the method as expected by the library. I am not sure if that is bad on part of library, or something wrong in my understanding.
I will take one example.
public class ViewManager {
public virtual void Customize(){
PrepareBaseView();
}
}
public class PostViewManager {
public override void Customize(){
base.Customize();
PreparePostView();
}
}
public class PreViewManager {
public override void Customize(){
PreparePreView();
base.Customize();
}
}
public class CustomViewManager {
public override void Customize(){
PrepareCustomView();
}
}
My question here is that how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?
Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?
how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?
There is no way to "know" this when you are subclassing and overriding a method. Proper documentation is really the only option here.
Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?
The only option here is to avoid the issue. Instead of allowing the subclass to override the method, it can be declared non-virtual, and call a virtual method in the appropriate place. For example, if you want to enforce that subclasses "call your version first", you could do:
public class BaseClass {
public void Method() // Non-virtual
{
// Do required work
// Call virtual method now...
this.OnMethod();
}
protected virtual void OnMethod()
{ // Do nothing
}
}
The subclasses can then "override" OnMethod, and provide functionality that happens after "method"'s work.
The reason this is required is that virtual methods are designed to allow a subclass to completely replace the implementation of the parent class. This is done on purpose. If you want to prevent this, it's better to make the method non-virtual.
This is why I feel virtual methods are dangerous when you ship them in a library. The truth is you never really know without looking at the base class, sometimes you have to fire up reflektor, read documentation or approach it with trial and error.
When writing code myself I've always tired to follow the rule that says:
Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
This is taken from http://msdn.microsoft.com/en-us/library/ms229011.aspx, however this is for Event design though I believe I read this in the Framework Design Guidelines book (http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756).
However, this is obviously not true, ASP.NET web forms for example require a base call on Page_Load.
So, long and short, it varies and unfortunately there is no instant way of knowing. If I'm in doubt I will omit the call initially.
The short answer is no. You can't enforce in what order the child calls the base method, or if it calls it at all.
Technically this information should be included in the base object's documentation. If you absolutely must have some code run before or after the child class' code than you can do the following:
1) Create a non-virtual function in the base class. Let's call it MyFunction
2) Create a protected virtual function in the base class. Let's call it _MyFunction
3) Have deriving classes extend the _MyFunction method.
4) Have MyFunction call _MyFunction and run the code it needs to run before or after calling it.
This method is ugly and would require a lot of extra code, so I recommend just putting a notice in the documentation.
The requirements of the base class should be documented by the library designer.
This issue is the reason why some libraries contain mainly sealed classes.
Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.
e.g.
public DerivedClass : BaseClass {}
Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?
It's not possible, why?
In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place.
Instead of using the is-a relationship, you would have to use the has-a relationship.
The language designers don't allow this on purpose so that you use inheritance more properly.
For example one might accidentally confuse a class Car to derive from a class Engine to get it's functionality. But an Engine is functionality that is used by the car. So you would want to use the has-a relationship. The user of the Car does not want to have access to the interface of the Engine. And the Car itself should not confuse the Engine's methods with it's own. Nor Car's future derivations.
So they don't allow it to protect you from bad inheritance hierarchies.
What should you do instead?
Instead you should implement interfaces. This leaves you free to have functionality using the has-a relationship.
Other languages:
In C++ you simply specify a modifier before the base class of private, public or protected. This makes all members of the base that were public to that specified access level. It seems silly to me that you can't do the same in C#.
The restructured code:
interface I
{
void C();
}
class BaseClass
{
public void A() { MessageBox.Show("A"); }
public void B() { MessageBox.Show("B"); }
}
class Derived : I
{
public void C()
{
b.A();
b.B();
}
private BaseClass b;
}
I understand the names of the above classes are a little moot :)
Other suggestions:
Others have suggested to make A() and B() public and throw exceptions. But this doesn't make a friendly class for people to use and it doesn't really make sense.
When you, for instance, try to inherit from a List<object>, and you want to hide the direct Add(object _ob) member:
// the only way to hide
[Obsolete("This is not supported in this class.", true)]
public new void Add(object _ob)
{
throw NotImplementedException("Don't use!!");
}
It's not really the most preferable solution, but it does the job. Intellisense still accepts, but at compile time you get an error:
error CS0619: 'TestConsole.TestClass.Add(TestConsole.TestObject)' is obsolete: 'This is not supported in this class.'
That sounds like a bad idea. Liskov would not be impressed.
If you don't want consumers of DerivedClass to be able to access methods DeriveClass.A() and DerivedClass.B() I would suggest that DerivedClass should implement some public interface IWhateverMethodCIsAbout and the consumers of DerivedClass should actually be talking to IWhateverMethodCIsAbout and know nothing about the implementation of BaseClass or DerivedClass at all.
What you need is composition not inheritance.
class Plane
{
public Fly() { .. }
public string GetPilot() {...}
}
Now if you need a special kind of Plane, such as one that has PairOfWings = 2 but otherwise does everything a plane can.. You inherit plane. By this you declare that your derivation meets the contract of the base class and can be substituted without blinking wherever a base class is expected. e.g. LogFlight(Plane) would continue to work with a BiPlane instance.
However if you just need the Fly behavior for a new Bird you want to create and are not willing to support the complete base class contract, you compose instead. In this case, refactor the behavior of methods to reuse into a new type Flight. Now create and hold references to this class in both Plane and Bird.
You don't inherit because the Bird does not support the complete base class contract... ( e.g. it cannot provide GetPilot() ).
For the same reason, you cannot reduce the visibility of base class methods when you override.. you can override and make a base private method public in the derivation but not vice versa. e.g. In this example, if I derive a type of Plane "BadPlane" and then override and "Hide" GetPilot() - make it private; a client method LogFlight(Plane p) will work for most Planes but will blow up for "BadPlane" if the implementation of LogFlight happens to need/call GetPilot(). Since all derivations of a base class are expected to be 'substitutable' wherever a base class param is expected, this has to be disallowed.
#Brian R. Bondy pointed me to an interesting article on Hiding through inheritance and the new keyword.
http://msdn.microsoft.com/en-us/library/aa691135(VS.71).aspx
So as workaround I would suggest:
class BaseClass
{
public void A()
{
Console.WriteLine("BaseClass.A");
}
public void B()
{
Console.WriteLine("BaseClass.B");
}
}
class DerivedClass : BaseClass
{
new public void A()
{
throw new NotSupportedException();
}
new public void B()
{
throw new NotSupportedException();
}
public void C()
{
base.A();
base.B();
}
}
This way code like this will throw a NotSupportedException:
DerivedClass d = new DerivedClass();
d.A();
The only way to do this that I know of is to use a Has-A relationship and only implement the functions you want to expose.
Hiding is a pretty slippery slope. The main issues, IMO, are:
It's dependent upon the design-time
declaration type of the instance,
meaning if you do something like
BaseClass obj = new SubClass(), then
call obj.A(), hiding is defeated. BaseClass.A() will be executed.
Hiding can very easily obscure
behavior (or behavior changes) in
the base type. This is obviously
less of a concern when you own both
sides of the equation, or if calling 'base.xxx' is part of your sub-member.
If you actually do own both sides of the base/sub-class equation, then you should be able to devise a more manageable solution than institutionalized hiding/shadowing.
I would say that if you have a codebase that you are wanting to do this with, it is not the best designed code base. It's typically a sign of a class in one level of the heirarchy needing a certain public signature while another class derived from that class doesn't need it.
An upcoming coding paradigm is called "Composition over Inheritance." This plays directly off of the principles of object-oriented development (especially the Single Responsibility Principle and Open/Closed Principle).
Unfortunately, the way a lot of us developers were taught object-orientation, we have formed a habit of immediately thinking about inheritance instead of composition. We tend to have larger classes that have many different responsibilities simply because they might be contained with the same "Real World" object. This can lead to class hierarchies that are 5+ levels deep.
An unfortunate side-effect that developers don't normally think about when dealing with inheritance is that inheritance forms one of the strongest forms of dependencies that you can ever introduce into your code. Your derived class is now strongly dependant on the class it was inherited from. This can make your code more brittle in the long run and lead to confounding problems where changing a certain behavior in a base class breaks derived classes in obscure ways.
One way to break your code up is through interfaces like mentioned in another answer. This is a smart thing to do anyways as you want a class's external dependencies to bind to abstractions, not concrete/derived types. This allows you to change the implementation without changing the interface, all without effecting a line of code in your dependent class.
I would much rather than maintain a system with hundreds/thousands/even more classes that are all small and loosely-coupled, than deal with a system that makes heavy use of polymorphism/inheritance and has fewer classes that are more tightly coupled.
Perhaps the best resource out there on object-oriented development is Robert C. Martin's book, Agile Software Development, Principles, Patterns, and Practices.
If they're defined public in the original class, you cannot override them to be private in your derived class. However, you could make the public method throw an exception and implement your own private function.
Edit: Jorge Ferreira is correct.
While the answer to the question is "no", there is one tip I wish to point out for others arriving here (given that the OP was sort of alluding to assembly access by 3rd parties). When others reference an assembly, Visual Studio should be honoring the following attribute so it will not show in intellisense (hidden, but can STILL be called, so beware):
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
If you had no other choice, you should be able to use new on a method that hides a base type method, return => throw new NotSupportedException();, and combine it with the attribute above.
Another trick depends on NOT inheriting from a base class if possible, where the base has a corresponding interface (such as IList<T> for List<T>). Implementing interfaces "explicitly" will also hide those methods from intellisense on the class type. For example:
public class GoodForNothing: IDisposable
{
void IDisposable.Dispose() { ... }
}
In the case of var obj = new GoodForNothing(), the Dispose() method will not be available on obj. However, it WILL be available to anyone who explicitly type-casts obj to IDisposable.
In addition, you could also wrap a base type instead of inheriting from it, then hide some methods:
public class MyList<T> : IList<T>
{
List<T> _Items = new List<T>();
public T this[int index] => _Items[index];
public int Count => _Items.Count;
public void Add(T item) => _Items.Add(item);
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
void ICollection<T>.Clear() => throw new InvalidOperationException("No you may not!"); // (hidden)
/*...etc...*/
}