Polymorphism vs Overriding vs Overloading

前端 未结 21 2784
北恋
北恋 2020-11-22 01:10

In terms of Java, when someone asks:

what is polymorphism?

Would overloading or overriding be

21条回答
  •  梦如初夏
    2020-11-22 01:15

    Here's an example of polymorphism in pseudo-C#/Java:

    class Animal
    {
        abstract string MakeNoise ();
    }
    
    class Cat : Animal {
        string MakeNoise () {
            return "Meow";
        }
    }
    
    class Dog : Animal {
        string MakeNoise () {
            return "Bark";
        }
    }
    
    Main () {
       Animal animal = Zoo.GetAnimal ();
       Console.WriteLine (animal.MakeNoise ());
    }
    

    The Main function doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.

    Edit: Looks like Brian beat me to the punch. Funny we used the same example. But the above code should help clarify the concepts.

提交回复
热议问题