Will the base class constructor be automatically called?

后端 未结 6 1508
孤街浪徒
孤街浪徒 2020-11-30 20:36
class Person
{
    public int age;
    public Person()
    {
        age = 1;
    }
}

class Customer : Person
{
    public Customer()
    {
        age += 1;
    }
         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 21:19

    base() is called by default but it can be used for other purpose such as :

    1. base()` method is used to pass the value to the parent class construct or
    2. to call the no-arg constructor of parent class .

    for example:

    Case 1: if parent have parametrized constructor but not default or no-arg constructor.

     class Person
     {
    
        private string FirstName;
        private string LastName;
        private string EmailAddress;
        private DateTime DateOfBirth;
    
        public Person(string firstName, string lastName, string emailAddress, DateTime dateOfBirth)
        {
            FirstName = firstName;
            LastName = lastName;
            EmailAddress = emailAddress;
            DateOfBirth = dateOfBirth;
    
        }
        }
    class Employee : Person
    {
        private double Salary { get; set; } = 0;
    
        public Employee(string firstName, string lastName, string emailAddress, DateTime dateOfBirth,double salary)
            :base(firstName,lastName,emailAddress,dateOfBirth)// used to pass value to parent constructor and it is mandatory if parent doesn't have the no-argument constructor.
        {
            Salary = salary;
        }
    }
    

    Case 2: when parent have more than one constructor along with default one.

    class Person
    {
    
        private string FirstName;
        private string LastName;
        private string EmailAddress;
        private DateTime DateOfBirth;
    
        public Person()
        {
            // some important intialization's to be done  
    
        }
    
        public Person(string firstName, string lastName, string emailAddress, DateTime dateOfBirth)
        {
            FirstName = firstName;
            LastName = lastName;
            EmailAddress = emailAddress;
            DateOfBirth = dateOfBirth;
    
        }
        }
    class PermanentEmployee : Person
    {
        public double HRA { get; set; }
        public double DA { get; set; }
        public double Tax { get; set; }
        public double NetPay { get; set; }
        public double TotalPay { get; set; }
    
        public PermanentEmployee(double hRA, double dA, double tax, double netPay, double totalPay) : base();
        {
            HRA = hRA;
            DA = dA;
            Tax = tax;
            NetPay = netPay;
            TotalPay = totalPay;
        }
    }
    

    Here we are calling a no-arg constructor manually by base() to perform some intilizations but doesn'e passed any value.

    Hope this will help you.

提交回复
热议问题