Hello. When I create an object of the inherited class. for example

using System; class A { public virtual void foo() { Console.WriteLine("this is virtual function"); } public void func() { Console.WriteLine("first function"); } } class B : A { public override void foo() { Console.WriteLine("this is override function"); } public void func2() { Console.WriteLine("second function"); } } class Program { static void Main() { A obj; B obj2 = new B(); obj = obj2; obj.foo(); Console.ReadKey(); } } 

and create an object of class B and assign it to obj = obj2, then an incomprehensible case arises. That is, I can only call functions (fields) of class A, but one exception is that I can call the function public override void foo () from class B. How is it possible that obj does not see the arguments of class B, but sees the overridden methods?

  • this is the essence of overlapping / overriding methods. Read about the PLO again. - teran 8:50 pm
  • possible duplicate.stackoverflow.com/q/699186/223826 - teran

1 answer 1

Here the problem, as I understand it, is weakly associated with the redefinition of methods.

Your obj variable is of type A Even assigning to it a reference to the type of an object of type B - the variable does not change its type. To make it a little clearer (I hope you know about the interfaces):

 interface IMyInterface { void foo(); } class MyClass : IMyInterface { void foo() {} void bar() {} } .............................. IMyInterface v = new MyClass(); v.foo(); //можно v.bar(); //нельзя 

We can say that we "do not know" that the reference to the object of the class MyClass is stored in v , we only know that this object supports the IMyInterface interface, because the object cannot be created from the interface. But we can create a variable of a more general type than a real value. In general, they usually do this in order to get rid of the implementation:

 void SendData(IData data) {...} 

The method gets an object that implements IData . In the context of the method, it doesn’t matter what type of object the object will be in; we will work only with the properties and methods provided by the IData interface

Another example:

 object v = new List<int>(); v.Add(5); // неа 

To better understand, you should read about polymorphism. When first studied, this can be difficult. But you need to take different sources, so that in the end you still need to understand, because without this, you will not advance further into the PLO.