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

你。 提交于 2019-12-02 00:09:54

You can only use the functions declared in the class you use.

abstract class Classification
{
  public abstract string type();
}

class PartTime : Classification
{
  public override string type() {...}
  public Job1() {...}
}

class FullTime : Classification
{
  public override string type() {...}
  public Job2() {...}
}
  • A object of type Classification can only use the type()
  • A object of the type PartTime can use type and Job1()
  • A object of the type FullTime can use type and Job2()

If you have an object like this:

Classification classification = new PartTime();

and you don´t know which special type, you have to cast this object to use other methods:

if (classification is PartTime)
{
  ((PartTime)classification).Job1();
}
else if (classification is FullTime)
{
  ((FullTime)classification).Job2();
}

Hope this helps.

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";
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!