프로그래밍 언어/C#

C# 추상 클래스 (abstract)

ShovelingLife 2022. 7. 28. 09:23

추상 클래스(abstract class)와 추상 메서드(abstract method)이다. 추상 메서드는 abstract 예약어가 지정되고 구현 코드가 없는 Method이다. 추상 메서드는 반드시 추상 클래스 안에서만 선언할 수 있으며, 추상 메서드를 하나라도 가지고 있으면 추상 클래스로 만들어줘야 한다.

특징

  • 추상 메서드에는 접근 제한자로 private를 사용할 수 없다.
  • new를 사용해 인스턴스로 만들 수 없다
  • 추상 메서드만을 가질 수 있다. 
abstract class Employee
{
    public int EmpID { get; private set; }
    public long Salary { get; set; }

    public Employee(int empId, long salary)
    {
        EmpID = empId;
        Salary = salary;
    }

    public abstract long CalcMonthSalary();        
    
    public virtual long CalcMonthSalary_()  //일반 Method도 구현할 수 있다.
    {
        return this.Salary / 12;
    }
}
class SalesPerson : Employee
{
    public double Incentive { get; set; }
    public SalesPerson(int empid, long salary, double incentive):base(empid, salary)
    {
        this.Incentive = incentive;
    }

    public override long CalcMonthSalary()
    {
        return this.Salary / 12 + (long)(this.Salary / 12 * Incentive * 0.01);
    }
}
class abstract_ex1
{
    static void Main()
    {
        Employee emp1 = new SalesPerson(1000, 30000000, 0);
        Console.WriteLine(emp1.CalcMonthSalary());
    }
}

출처 : https://smartseoullife.tistory.com/43