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

前端 未结 2 928
无人共我
无人共我 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条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 16:02

    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.

提交回复
热议问题