c#中接口与抽象类区别

转载自:https://www.c-sharpcorner.com/article/overview-of-abstract-class-and-interface/

Introduction

In this article, I will explain about abstract class and interface, the most important topics to cover. Most of the interviewers ask about the abstract class and interface. I will cover all the possible interview questions which I have faced during my interviews.

Let’s start.

What is an abstract class?

A class with the abstract modifier indicates that it is an abstract class. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

Example

using System;  
  
namespace AbstractClass_Demo  
{  
    public abstract class Employee  
    {  
        public string firstName;  
        public string lastName;  
        public abstract void FullName();  
    }  
  
    public class PermanantEmployee : Employee  
    {  
        public int Salary;  
  
        public override void FullName()  
        {  
            Console.WriteLine("Full Name:"+ firstName + " "+ lastName + "-Parmanant Employee");  
        }  
    }  
  
    public class ContactEmployee : Employee  
    {  
        public int HourlyRate;  
        public override void FullName()  
        {  
            Console.WriteLine("Full Name:" + firstName + " " + lastName + "-Contract Employee");  
        }  
    }  
}  
using AbstractClass_Demo;  
using System;  
  
namespace AbstractClass_Demo  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            PermanantEmployee pe = new PermanantEmployee();  
            pe.firstName = "Farhan";  
            pe.lastName = "Ahmed";  
            pe.FullName();  
            pe.Salary = 50000;  
  
            Console.WriteLine("Permanant Employee Salary:"+pe.Salary);  
            Console.WriteLine("....................................");  
  
            ContactEmployee ce = new ContactEmployee();  
            ce.firstName = "Rahul";  
            ce.lastName = "Sharma";  
            ce.FullName();  
            ce.HourlyRate = 500;  
            Console.WriteLine("Contract Employee Hourly Rate:" + pe.Salary);  
            Console.ReadLine();  
  
        }     
    }  
} 

Output

output1

Features of an abstract class

  1. An abstract class cannot be instantiated.
  2. An abstract class may contain abstract methods and accessors.
  3. An abstract class cannot be sealed. The sealed modifier prevents a class from being inherited.
  4. An abstract class requires to be inherited.
  5. A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

What are abstract methods?

A method with abstract modifier indicates that this is an abstract method. Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods.

public abstract void MyMethod();  

Features of an abstract method

  1. An abstract method is implicitly a virtual method.
  2. Abstract method declarations are only permitted in abstract classes.
  3. An abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature.
  4. The implementation is provided by a method override, which is a member of a non-abstract class.
  5. It is an error to use the static or virtual modifiers in an abstract method declaration.

When to use Abstract class in C#?

In various implementations, if they are of the same kind and use common behavior or status, then an abstract class is better to use.

What is an interface?

An interface is a contract that contains only the declaration of the methods, properties, and events, but not the implementation. It is left to the class that implements the interface by providing the implementation for all the members of the interface. The Interface makes it easy to maintain a program.

Example

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace Interface_Demo  
{  
    public interface IEmployeeBonus  
    {  
        decimal CalculateBonus();  
    }  
}  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace Interface_Demo  
{  
    public class Employee : IEmployeeBonus  
    {  
        public string firstName;  
        public string lastName;  
        public int salary;  
        public decimal CalculateBonus()  
        {  
           return salary * 0.10M;  
        }  
    }  
}  
using System;  
  
namespace Interface_Demo  
{  
    class Program:Employee  
    {  
        static void Main(string[] args)  
        {  
            Employee employee = new Employee();  
            employee.firstName = "Farhan";  
            employee.lastName = "Ahmed";  
            employee.salary = 50000;  
            employee.CalculateBonus();  
  
            Console.WriteLine("Employee Name:"+employee.firstName + "" + employee.lastName);  
            Console.WriteLine("Employee Salary:"+employee.salary);  
            Console.WriteLine("Employee Bonus:"+employee.CalculateBonus());  
            Console.ReadLine();  
        }  
    }  
}  

Output

output2

Features of interface

  1. An Interface contains only the signature of methods
  2. An Interface has no Implementation on its own
  3. An Interface is used to implement multiple inheritances in code.
  4. It defines a static set of methods and their arguments
  5. Variables in Interface must be declared as public, static and final
  6. Methods in an Interface must be declared as public and abstract
  7. A class implementing an Interface must implement all of its methods
  8. An Interface can derive from more than one Interface

Advantages of interface

  1. Interfaces facilitate parallel application development.
  2. They are great for implementing Inversion of Control or Dependency Injection.
  3. Interfaces enable mocking for better unit testing.
  4. Interfaces allow us to develop very loosely coupled systems.
  5. Interfaces also allow us to implement polymorphic behavior.

If a class inherits an interface, what are the 2 options available for that class?

  • Option 1
    Provide Implementation for all the members inherited from the interface.

  • Option 2
    If the class does not wish to provide Implementation for all the members inherited from the interface, then the class has to be marked as abstract.

When to use interface?

If various methods share only methods signature, then it is better to use interface. The interface allows multiple inheritances.

What is the difference between abstract class and interface?

Abstract ClassInterface
Abstract classes can have implementations for some of its membersAn interface can’t have an implementation for any of its members
An abstract class can have fieldsInterfaces cannot have fields
An abstract class can inherit from another class or another interface.An interface can inherit from another interface only and cannot inherit from any class.
A class cannot inherit from multiple classes at the same time.A class can inherit from multiple interfaces at the same time
Abstract class members can have access modifiersInterface members cannot have access modifiers. It is by default public.
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值