0
So when do we use virtual methods and when do we use abstract classes?
1 Answer
+ 1
An abstract class can be inherited but not instancedâș
thats like when you work with others and dont want them to do it by mistake, or if you want to ensure you wont forget it đ
A virtual method is used when you probably want to redefine a method in a subclass. Then to do it you just use the "override" word.
đ
For example:
using System;
namespace VirtualTesting
{
class Program
{
static void Main(string[] args)
{
Animal someanimal = new Animal();
Animal neko=new Gato();
someanimal.talk();
neko.talk();
Console.ReadKey();
}
}
class Animal
{
public virtual void talk()
{
Console.Write("I'm an animal");
}
}
class Gato : Animal
{
public override void talk()
{
Console.Write("Im a cat");
}
}
}
results:
I'm an animal
I'm a cat
You will get different results by doing these:
1. using "abstract" before "class Animal" -> wont workđ. unless you erase the "someanimal" variable đ
2. removing "virtual" and "override" words -> will show only the generic animal words
Hope you understand, because I'm not so good in English đ