Override (C # reference)

Source: Internet
Author: User
Example 

This example definesEmployeeAnd a base class namedSalesemployee.SalesemployeeClass includes an additional attributeSalesbonus, And rewrite the method.CalculatepayTo take this attribute into account.

Codes
Using system;
Class testoverride
{
Public class employee
{
Public string name;

// Basepay is defined as protected, so that it may be
// Accessed only by this class and derrived classes.
Protected decimal basepay;

// Constructor to set the name and basepay values.
Public Employee (string name, decimal basepay)
{
This. Name = Name;
This. basepay = basepay;
}

// Declared virtual so it can be overridden.
Public Virtual decimal calculatepay ()
{
Return basepay;
}
}

// Derive a new class from employee.
Public class salesemployee: Employee
{
// New field that will affect the base pay.
Private decimal salesbonus;

// The constructor cballs the base-class version, and
// Initializes the salesbonus field.
Public salesemployee (string name, decimal basepay,
Decimal salesbonus): Base (name, basepay)
{
This. salesbonus = salesbonus;
}

// Override the calculatepay Method
// To take bonus into account.
Public override decimal calculatepay ()
{
Return basepay + salesbonus;
}
}

Static void main ()
{
// Create some new employees.
Salesemployee employee1 = new salesemployee ("Alice ",
1000,500 );
Employee employee2 = new employee ("Bob", 1200 );

Console. writeline ("employee" + employee1.name +
"Earned:" + employee1.calculatepay ());
Console. writeline ("employee" + employee2.name +
"Earned:" + employee2.calculatepay ());
}
}

Output

Employee Alice earned: 1500
Employee Bob earned: 1200

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.