Hi Everyone,
I had tried the following programs.
1 st program---------------------------
public class a
{
public void run()
{
console.writeline("hai");
}
}
public class b:a
{
public void run()
{
console.writeline("hello");
}
class c
{
public static void main()
{
b b1 =new b();
b1.run();
a a1=new a();
a1.run();
}
}
2 ND program----------------
public class a
{
public vitual void run()
{
console.writeline("hai");
}
}
public class b:a
{
public override void run()
{
console.writeline("hello");
}
class c
{
public static void main()
{
b b1 =new b();
b1.run();
a a1=new a();
a1.run();
}
}
note:
These two programs print same output means for which i had created object for class ,that method will be called.Then what is the role of Virtual and Override.We already know that override is used it code replacement,but what is the another use in above program...
Thanks,
Maheswar
Loading
VulpesPosted Sep 30, 2011, 4:35 AM
If a method is declared to be virtual then it's the runtime type of the variable on which it's called that determines which version of the method gets called, not its compile time type.
The compile time type of 'a2' is 'a' but its runtime type is 'b' because 'b1' refers to a 'b' object. Consequently, 'b's version (or override) of the run() method gets called and prints "hello" to the console.