C# Cannot access child public method from abstract parent class object

前端 未结 2 950
无人共我
无人共我 2021-01-22 15:27

I\'m learning OOAD and trying to implement class relationship with inheritance but there is an issue here is the code

Parent Class

names         


        
2条回答
  •  萌比男神i
    2021-01-22 15:38

    When casting you're object into another object type, that called Polymorphism. This translate that you can only use the methods and properties that exposed to the destination object type, which is Classification which doesn't know your method.

    Simple example i made:

    using System;
    
    namespace Program
    {
        public class Program
        {
            public static void Main()
            {
                Dog rex = new Dog();
                Animal rexAsAnimal = rex;
    
                // Can access 'MakeSound' due the fact it declared at Dog (Inherited by Animal)
                Console.WriteLine(rex.MakeSound()); // Output: Bark
    
                // Compilation error: rexAsAnimal is defined as 'Animal' which doesn't have the 'Bark' method.
                //Console.WriteLine(rexAsAnimal.Bark()); // Output when uncomment: Compilation error.
    
                // Explicitly telling the compiler to cast the object into "Dog"
                Console.WriteLine(((Dog)rexAsAnimal).Bark()); // Output: Bark
            }
        }
    
        public abstract class Animal
        {
            public abstract string MakeSound();
        }
    
        public class Dog : Animal
        {
            public override string MakeSound() { return Bark(); }
            public string Bark()
            {
                return "Bark";
            }
        }
    }
    

提交回复
热议问题