Not sure when to use an abstract property and when not

后端 未结 5 1144
野性不改
野性不改 2020-12-04 12:52

I\'m not really sure what looks better or when do I really use in abstract classes and properties, or when to use non abstract properties. I\'ll try to make a simple example

5条回答
  •  感情败类
    2020-12-04 13:45

    Use abstract when all sub-classes have to implement the method/property. If there's no need for each and every sub-class to implement it, then don't use it.

    As for your example, if SecondName is not required for each person, then there's no need to make an abstract property in the base class. If on the other hand, every person does need a second name, then make it an abstract property.

    Example of correct usage of an abstract property:

    public class Car
    {
        public abstract string Manufacturer { get; }
    }
    
    public class Odyssey : Car
    {
        public override string Manufacturer
        {
             get 
             {
                 return "Honda";
             }
        }
    }
    
    public class Camry : Car
    {
        public override string Manufacturer
        {
             get 
             {
                 return "Toyota";
             }
        }
    }
    

    Making Maker abstract is correct because every car has a manufacturer and needs to be able to tell the user who that maker is.

提交回复
热议问题