Abstract method declaration - virtual?
On MSDN I have found that it is a error to use "virtual" modifier in an abstract meth开发者_如何学编程od declaration. One of my colleagues, who should be pretty experienced developer, though uses this in his code:
public abstract class BusinessObject
{
public virtual void Render(){}
public virtual void Update(){}
}
Also it correct or not?
It can make sense if the abstract class is providing an optional point where inherited classes can change the behaviour.
So this way the inherited classes will not be forced to implement it but they can if they need to.
Usually this method is called by the abstract class:
public AddFoo(Foo f)
{
// ...
OnAddedFoo(f);
}
Here it makes sense to have OnAddedFoo
as virtual
and not abstract
.
I guess the MSDN means you can't use the virtual
and abstract
modifier on a method at the same time.
You can either do
public virtual void Render() {}
which means that an inheriting class can override this method.
Or you can do
public abstract void Render();
which means that an inheriting class must override this method.
Those aren't abstract methods, they're empty default ones. The difference is you don't HAVE to override them (if you don't, nothing will happen).
It might help your understanding to see them formatted like:
public abstract class BusinessObject
{
public virtual void Render()
{
}
public virtual void Update()
{
}
}
You probably refer to this sentence
You cannot use the virtual modifier with the static, abstract, private or override modifiers.
This mean that you can not use this in method declaration a method can't be at the same time virtual and abstract.
So the usage that you have presented is fine, because the class is abstract this mean that you can have there some abstract methods (with out implementation that have to be implemented by child class) and virtual method (with implementation that can be override in child class).
Follwing code means that you must ovveride this method in inherited class and you can't put some logic in abstract method body:
public abstract void Render();
But if you declare virtual method you can put some logic inside it and can ovveride
public virtual void Render()
{
// you can put some default logic here
}
精彩评论