开发者

Dynamic Polymorphism : Doubt

开发者 https://www.devze.com 2023-02-06 22:02 出处:网络
I have this code: namespace ClassLibrary1 { public class Testing_Class { public string A() { int i = 3; Console.Write(\"Value if i\" + i);

I have this code:

namespace ClassLibrary1
{
    public class Testing_Class
    {
        public string A()
        {
            int i = 3;
            Console.Write("Value if i" + i);
            string a = "John";
            return a;
        }


    }

    public class Testing : Testing_Class
    {
        public string A()
        {
            string a = "John";
            Console.Write(a);
            return a;
        }

    }



    public class Test
    {
        public void foo()
        {
          开发者_StackOverflow  Testing MyTesting = new Testing();
            MyTesting.A(); //Dynamic Polymorphism ??

        }
    }

    }

When I am calling MyTesting.A() is this a Dynamic Polymorphism? I have not included any Virtual Keyword or any Override here?

Your inputs?


Nope, there's no polymorphism going on here. You've got a non-virtual call to a non-virtual method. Unlike some other languages, methods and properties in C# are non-virtual by default.

In order to demonstrate polymorphism really working, you'd want to:

  • Declare the method virtual in the base class
  • Use the override modifier in the derived class
  • Use a variable with a compile-time type of the base class for the invocation, but having initialized it with an object of the derived type.

Here's a short but complete program demonstrating all that:

using System;

class Base
{
    public virtual void Foo()
    {
        Console.WriteLine("Base.Foo");
    }
}

class Derived : Base
{
    public override void Foo()
    {
        Console.WriteLine("Derived.Foo");
    }
}

class Test
{
    static void Main()
    {
        Base x = new Derived();
        x.Foo(); // Prints Derived.Foo
    }
}


No, this is not polymorphism. You're creating a new member with the same name on the subclass, not overriding the parent class' member. If you were to refer to your instance as an instance of the parent class, it would actually call the parent class' member, not the child class. Try it out:

        Testing_Class MyTesting = new Testing();
        MyTesting.A();


You are not overriding but hiding. Since you did not mark the method.

That is you can hide virtual methods, but you cannot override normally derived methods.

        class TestBase
        {
            public void GoForIt() {}
        }

        class Test : TestBase
        {
            public virtual new void GoForIt() {}
        }


        class Other : Test
        {
            public override void GoForIt() {}
            public new void GoForIt() {}
        }

if you 'forget' the new keyword, the compiler will warn you:

The keyword new is required on "Other.GoForIt()" because it hides inherited member

0

精彩评论

暂无评论...
验证码 换一张
取 消