I have these classes:
class A
{
public int Foo()
{
return 5;
}
}
class B : A
{
public int Foo()
{
return 1;
}
}
and I use them like this:
B b = new B();
int x = b.Foo();
and although Foo() in the base class isn't virtual, or in the derived class - it hasn't the override keyword, still x equals 1. Then, what is the use of the virtual and override keywords?
Polymorphism allows type B to be treated as type A.
A b = new B();
int x = b.Foo(); // x will be 1 if virtual, 5 if not.
Assuming this is C#:
You didn't override Foo. You hid the Foo of the baseclass. This means that if you call foo an a variable with the static type B you will get B.Foo() and calling on the static type A (even if the type is B at runtime) will give you A.Foo().
Your code should give a compiler warning, since you're hiding the base method without using the new keyword.
B b = new B();
int x = b.Foo();//calls B.Foo
A a = b;//Runtime type B, compiletime type A
a.Foo(); // calls A.Foo
If you had overridden Foo then you'd get B.Foo() in both cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With