So when do we use virtual methods and when do we use abstract classes? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

So when do we use virtual methods and when do we use abstract classes?

26th Jul 2016, 2:03 PM
Ihusaan Ahmed
Ihusaan Ahmed - avatar
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 😜
28th Jul 2016, 6:47 AM
Julio González
Julio González - avatar