I am using C# with Unity3d.
When I use Monobehaviour and create an Update method, I don't need to use the override keyword.
When I create my own class and override a function, I do need to use the override keyword.
Why is that? Why do I not need the override keyword when creating the Update method?
I think your confusion comes from the fact that Unity does something special about these methods (Update, Start, Awake, etc). You can declare them as private and even then they will be called. That's not achievable using the language unless you use reflection, but I was told they don't use it, so I don't know what they do. And honestly, it doesn't matter. Because you can think as this being an exception to the language, that is, these methods will be called if you implement them. Simply that.
For all the rest, you have to follow the language. Here is a rough explanation:
You can or have to override a method if it is marked as abstract or virtual in the base class.
A method is abstract when the base class wants its children to implement it. A method is virtual when the base class offers an implementation of it but also offers an opportunity for the children to implement/modify that method.
So why can't all methods be "overridable"? To protect the base class developer's intention. You'd be changing the behaviour of a base class, you don't know if the base class developer would like you to do this. It's like a security lock. So that's why you have the three words abstract, virtual and override, to communicate the API intentions from the base class to their children.
You need to use the override, when you derive a class from another class and you need to change the code of a method of the base class that is virtual. This way the inheritted method of the base class can have a different behaviour -more suitable- for the derived class.
More generally, as it is stated in MSDN:
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
Related
I'm trying to understand abstract classes in c# better.
I know that in abstract classes you MUST override abstract methods and MAY override virtual methods..
my question is:
can I override non virtual methods? (I know that normally I can't - but maybe with abstract classes it's different?) or will it be like hiding ?
also, as I read here How to force call a C# derived method (the first answer) - it seems to me that because non virtual methods statically linked at compile time and can't be changed - I would not be able to call the methods in the derived class ,never? if so - what is the point of hiding a method?
I'm trying to understand abstract classes in c# better.
OK, then lets correct your mistakes, because you have some completely wrong ideas about abstract classes here.
I know that in abstract classes you MUST override abstract methods and MAY override virtual methods.
Absolutely not; the first part of that sentence is completely wrong. There is no requirement whatsoever in an abstract class to override an abstract method.
A non-abstract class is called a concrete class. The real rules are:
A concrete class must override all abstract methods of all its abstract base classes with concrete methods; it can do so either itself, or via one or more of its base classes.
This should make sense: you can't make an instance of a concrete class until every abstract method is implemented; otherwise you could invoke a method that has no implementation, and that would be bad.
Any derived class may override a non-sealed virtual method of any of its base classes.
can I override non virtual methods?
No. You can overload non-virtual methods and you can hide existing non-virtual methods, but you cannot override them.
it seems to me that because non virtual methods statically linked at compile time and can't be changed - I would not be able to call the methods in the derived class ,never?
Of course not. You call the methods of the derived class by converting the receiver to the derived class.
what is the point of hiding a method?
Duplicate of:
Is method hiding ever a good idea
Here's a BONUS QUESTION that you did not ask. See if you can answer it.
Can a method be marked as both abstract and override? If no, why not? If yes, give an example and explain why you would want to.
If you can answer that question correctly then you probably have a good understanding of abstract methods. The solution is here.
No, you can't. They must have virtual keyword. Good example here,similarThis one as well
I would advise taking a closer look into what you can do with OOP
In reference to your question, you can only override a virtual class, another of example instead of hiding methods would be:
However you can use inheritance, to use the controls from your base class. This should be done when both classes are related, to prevent creating duplicate code.
An example of this would be an individual person : Human, okay so here we use ('type of' :) stating that a person is a type of human. This is the basic use of inheritance.
This shouldn't be done if they are not related, this may seem quicker when you are doing it, however when you look back at your application 3months on you will say "Why did I do that?".
An example of this would be, this base class has a method close to what I am looking for, you need to make a comparison, is it Really? Should I actually do this?
The msdn article provided will give you the information you need to progress with this. Enjoy OOP
You have a little misunderstanding:
in abstract classes you MUST override abstract methods and MAY override virtual methods.
That sentence should really be:
in concrete classes that derive from an abstract class, you MUST override abstract methods and MAY override virtual methods, either in that class itself, one of its parent classes, or one of its subclasses.
You can use the new keyword to shadow, or hide, non-virtual methods, so yes it will be hiding and not overriding.
If you hide a method in a subclass, and then want to call the method as it appeared in the base class, cast the subclass as the to the base class type, as done in the second example here.
or am I missing something basic here??..
since sealed method avoids it to be overridden in the derived class and virtual allows it to
sealed is for preventing a subclass from overriding virtual methods you overrode.
The virtual keyword will let you (or someone using your code) override a given method with their own logic.
The abstract keyword will force you (or someone else using your code) to override it with your own logic.
The sealed keyword will let you (or someone using your code) prevent any further modification of a method.
An overriden method can be overriden again if you don't add "sealed".
When you think of these keywords, think of both scenarios: you can code for yourself, or you can create DLLs and code libraries for others to use. The latter scenario will often warrant the use of sealed, abstract and virtual.
Hope this helps!
Methods do not to be sealed or virtual. You do not need to specify anything, which will in turn not let derived classes override them.
Methods can me virtual, but only classes can be sealed.
Sealed classes can not be inherited from.
Source:
http://msdn.microsoft.com/en-us/library/88c54tsw(v=vs.71).aspx
EDIT:
Ok, I was wrong, a method can be sealed, but only one that already overrides another, the keyword then prevents further overriding of the method.
Source:
http://msdn.microsoft.com/en-us/library/aa645769(v=vs.71).aspx
Is a virtual method compulsory to override by its subclass?
If a method is not virtual (or abstract), it can't be overriden in the sub class. The only option then is to use the new keyword to hide the inherited method, but this is generally not a recommended practice, since casting the instance of the sub class to the parent class and calling the method will cause the parent class method to be called instead, and that is probably not the intended functionality.
So in short, yes it needs to be virtual to override, but no you dont have to override it. If you don't, the base class version will be called instead. But if you do override it, even if you cast the object to it base class type, the derived version of the method will be called, unlike for hiding the method with new.
It's good to know the difference between overriding and hiding the method, since at first glance, and if you test it, it might look like it does the same thing, but will come back to bite you later when the program don't work as expected, and you have no idea why.
No, when you are using "virtual" keyword, it's up to you whether you want to override or not. When you use "abstract", you need to override the method in the derived class. For more information, please see:
virtual (C#) (the keyword)
abstract (C#) (the modifier)
No. It can be overriden by a sub class, but does not have to be.
If you want to enforce overriding by subclasses, use abstract in an abstract class, or use an interface (meaning you have to implement all declared members).
Is a virtual method is compulsory to override by it's sub class?
No.
Can I Override a method which is NON-Virtual in parent class ?
No.
What is YES then ?
You must implement Abstract method of parent class (if derived class is non-abstract)
Can I write Virtual keyword on Static method
NO, Because these two are just opposite words. Virtual means compiler does not know at compile time which method to be called. Static means , for sure , your compiler knows which method will be called.
How do I stop my current class' subclasses to no Override my method ?
Mark it with sealed keyword.
Is Abstract method a virtual also ?
YES. That's why we cant explicitly mark abstract method virtual as well.
Is Override and Overload same ?
Off-course not! Overloading is having 2 methods with same name but which works on different set of input parameters.
When shall I Mark a method as Virtual ?
When you are using polymorphism and you are not sure about the type of the object passes to your method until runtime, and you want your subclasses to have different behavior then mark the method as Virtual.
e.g. You have
class Law
{
public void Punish(Minister any)
{
if (any.Corruption() == true)
{
... do whatever public wants...
}
}
}
And you have Hierarchy of Minister classes -Ministers, CentralGOVTMinisters , StateGOVTMinisters , DistrictAuthorityMinisters etc. And you know that Whatever defined in Minister class for Corruption() method can be used by many derived class but for few ministers Corruption laws are different (they have supreme powers may be !) , so there you override the Corruption() and everywhere else your derived classes use the implementation of Corruption() in Minister class (base of all minister).
Yes, if a method is not marked virtual or abstract it cannot be overridden. The only exception is when declaring an interface method you don't need to use it because an interface method is virtual by definition. When you implement this interface you need to use virtual or abstract if you want to be able to derive from the class implementing the interface and be able to override the method.
It is not compulsory to override virtual methods that are not abstract.
It is compulsory to implement abstract methods unless you also mark your class abstract.
No, it is not mandatory to override a virtual method in a derived class.
yes to override you need to write virtual keyword. or write keyword abstract method.
No, it just means that you can override it, not that you have to. Abstract is the keyword if you want to make it mandatory for the subclass to implement it.
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.
I was doing some code review today and came across an old code written by some developer. It goes something like this
public abstract class BaseControl
{
internal abstract void DoSomething();
}
If you have a derived class within the same assembly, it would work
public class DerivedControl : BaseControl
{
internal override void DoSomething()
{
}
}
But deriving the base class in a different assembly would give compile time error
DerivedControl does not implement inherited abstract member 'BaseControl.DoSomething()
That got me thinking. Why would anyone declare a method as internal abstract ?
The original programmer wanted to make a derived control available to client code. But prevent the client from inheriting and messing with the virtual method. That's not a bad idea, it is usually easy to break a base class by overriding a method and doing something like forgetting to call the base class method.
One obvious case is where the method receives or returns an internal type. For example, the core methods of the WPF Transform classes process some internal interop types, which WPF doesn't expose as part of its public API. Because the signature includes internal types, the method can't be public or protected. And yet clearly it's appropriate (necessary!) for the various Transform classes to work polymorphically. Therefore the base methods in Transform/GeneralTransform have to be internal.
Another, but related reason is to prevent external derivation. After all, the WPF architects could have exposed a "safe" version of the internal interop types in a protected abstract method, so that users could create their own Transform classes. They didn't because they didn't want to have to cope with the ways that people might use that capability, e.g. creating non-affine transforms. Allowing external derivation would have made the job of other classes in WPF hugely more complex, so the architects decided to allow only "approved" derived classes by making an abstract method internal.
My initial reaction was that there is no good reason, if you want to prevent external inheritance then you should mark the class internal. But that means that the class is totally hidden to other assemblies.
I suppose this method prevents external inheritance while retaining visibility.
By defining a method as internal abstract you want to make sure that only the class in the same assembly can have its implementation for your method.
now if you distribute a dll of it this will avoid the client to inherit and mesup the implementation.