Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism and inheritance

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?

like image 268
petko_stankoski Avatar asked Jul 09 '26 01:07

petko_stankoski


2 Answers

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.
like image 110
Pubby Avatar answered Jul 10 '26 13:07

Pubby


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.

like image 27
CodesInChaos Avatar answered Jul 10 '26 14:07

CodesInChaos