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

c#中接口与抽象类区别_第1张图片

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

c#中接口与抽象类区别_第2张图片

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 Class Interface
Abstract classes can have implementations for some of its members An interface can’t have an implementation for any of its members
An abstract class can have fields Interfaces 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 modifiers Interface members cannot have access modifiers. It is by default public.

你可能感兴趣的:(C#)