override in C#

  • Thread starter Thread starter Cyrus Chiu
  • Start date Start date
C

Cyrus Chiu

if a subclass's property or method is declared "override", what is the
different between the one without this keyword if the superclass contain the
same method/property name?
 
Cyrus Chiu said:
if a subclass's property or method is declared "override", what is the
different between the one without this keyword if the superclass contain the
same method/property name?

If you don't include the keyword, the new method *hides* the old method
instead of overriding it. That means it doesn't act polymorphically.
Suppose you have a virtual method in class Base called Foo, a method
which overrides it in class Derived1 which derives from base, and a
method which hides Foo in class Derived2 which also derives from base,
then:

Base b = new Base();
Base b1 = new Derived1();
Base b2 = new Derived2();

b.Foo(); // Calls Base.Foo
b1.Foo(); // Calls Derived1.Foo due to polymorphism
b2.Foo(); // Calls Base.Foo - Derived2.Foo doesn't override it


Derived1 d1 = new Derived1();
Derived2 d2 = new Derived2();

d1.Foo(); // Calls Derived1.Foo
d2.Foo(); // Calls Derived2.Foo
 
Back
Top