C# interview questions: Difference Between Abstract Class and Interface in C#

Difference Between Abstract Class and Interface in C

In C#, both abstract classes and interfaces are used to define abstract types that specify a set of functionalities that other classes must implement. However, they have different rules, use cases, and behaviors. Let’s dive into the key differences, explain when to use each, and provide code examples to help illustrate their uses.

Quick Answer

  • Abstract Class: Can provide both method definitions and implementations. Used when classes share a common base and behavior but also need to allow some method implementations.
  • Interface: Only defines method signatures and properties (until C# 8.0, which allows default implementations). Used when unrelated classes need to implement similar functionalities.

What is an Abstract Class in C#?

An abstract class is a class that cannot be instantiated directly. It allows you to define methods that must be implemented by any subclass. It can also contain implemented methods (non-abstract methods) that provide shared functionality.

Example:

public abstract class Animal
{
    // Abstract method (must be implemented by subclasses)
    public abstract void MakeSound();

    // Concrete method (shared implementation)
    public void Sleep()
    {
        Console.WriteLine("Sleeping...");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

What is an Interface in C#?

An interface is a blueprint of a class, meaning it only contains method and property declarations. Classes or structs that implement an interface must provide the implementation for all of its members.

Example:

public interface IAnimal
{
    void MakeSound();
    void Sleep();
}

public class Dog : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Bark");
    }

    public void Sleep()
    {
        Console.WriteLine("Sleeping...");
    }
}

5Ws Explanation

1. What:

  • Abstract Class: A class that cannot be instantiated and may have both abstract (unimplemented) and concrete (implemented) methods.
  • Interface: A contract that defines only method and property signatures, without implementation, but with default implementations available from C# 8.0 onwards.

2. Why:

  • Use an abstract class when you need to share code between related classes but still want to enforce implementation of certain behaviors in derived classes.
  • Use an interface when unrelated classes should implement the same set of functionalities.

3. When:

  • Use abstract classes when creating a base class with both defined and undefined behaviors.
  • Use interfaces when enforcing that multiple, possibly unrelated, classes provide the same functionalities.

4. Where:

  • Abstract classes are used when you have a base class that shares common behavior and state.
  • Interfaces are used when you want multiple classes to implement a set of methods, regardless of their place in the inheritance hierarchy.

5. Who:

  • Developers use abstract classes when designing a family of related classes with some shared functionality.
  • Developers use interfaces when designing classes that may not share a common ancestor but need to adhere to the same set of behaviors.

Code Examples

Abstract Class Example:

public abstract class Vehicle
{
    public abstract void Start();
    public void Stop()
    {
        Console.WriteLine("Vehicle Stopped.");
    }
}

public class Car : Vehicle
{
    public override void Start()
    {
        Console.WriteLine("Car Started.");
    }
}

public class Motorcycle : Vehicle
{
    public override void Start()
    {
        Console.WriteLine("Motorcycle Started.");
    }
}

Interface Example:

public interface IVehicle
{
    void Start();
    void Stop();
}

public class Car : IVehicle
{
    public void Start()
    {
        Console.WriteLine("Car Started.");
    }

    public void Stop()
    {
        Console.WriteLine("Car Stopped.");
    }
}

public class Motorcycle : IVehicle
{
    public void Start()
    {
        Console.WriteLine("Motorcycle Started.");
    }

    public void Stop()
    {
        Console.WriteLine("Motorcycle Stopped.");
    }
}

Key Points & Tips

  • Abstract Classes:

    • Can have fields, constructors, and implemented methods.
    • Use abstract classes when you want to provide common functionality that all subclasses share.
    • Subclasses of an abstract class are often closely related.

    提示1:当你需要为子类提供共享功能时使用抽象类。

  • Interfaces:

    • Cannot have fields or constructors, though C# 8.0 allows default implementations.
    • Use interfaces when you need to enforce that unrelated classes follow the same contract.

    提示2:当不相关的类需要遵循相同的合同时,使用接口。

  • Multiple Inheritance:

    • C# doesn’t support multiple inheritance with classes, but a class can implement multiple interfaces.

    提示3:虽然 C# 不支持多重继承,但类可以实现多个接口。


Comparison: Abstract Class vs Interface

Feature Abstract Class Interface
Multiple Inheritance Cannot inherit multiple abstract classes Can implement multiple interfaces
Method Implementation Can have both abstract and concrete methods No concrete methods before C# 8.0
Fields and Properties Can have fields and properties Can only have properties (no fields)
Constructors Can have constructors Cannot have constructors
Access Modifiers Can have access modifiers (public, protected, etc.) Only public by default
Typical Usage For related objects with shared functionality For defining behavior across unrelated objects

Interview Questions (中英对照)

Q1. What are the key differences between an abstract class and an interface in C#?

The main differences are:

  1. An abstract class can contain both abstract and concrete methods, while an interface can only contain method signatures (unless using default implementations in C# 8.0).
  2. A class can implement multiple interfaces, but it can inherit from only one abstract class.

Q1. C# 中抽象类和接口的主要区别是什么?

主要区别包括:

  1. 抽象类可以包含抽象方法和具体方法,而接口只能包含方法签名(除非使用 C# 8.0 中的默认实现)。
  2. 一个类可以实现多个接口,但只能继承一个抽象类。

Q2. When would you choose an abstract class over an interface?

You would choose an abstract class when you want to provide some common functionality across all subclasses, in addition to enforcing method implementations. For example, if all subclasses should inherit some default behavior, an abstract class is a good choice.

Q2. 你会在何时选择抽象类而不是接口?

当你想在所有子类中提供一些共享功能并且强制执行方法实现时,你会选择抽象类。例如,如果所有子类都应该继承一些默认行为,抽象类是一个不错的选择。


Q3. Can a class implement multiple interfaces and extend an abstract class at the same time?

Yes, a class in C# can extend one abstract class and implement multiple interfaces.

Q3. C# 中,一个类可以同时实现多个接口并继承一个抽象类吗?

是的,C# 中,一个类可以继承一个抽象类并实现多个接口。


Q4. Can you have a constructor in an interface?

No, interfaces cannot have constructors because they cannot contain any implementation, and constructors are tied to object creation.

Q4. 接口中可以有构造函数吗?

不可以,接口不能有构造函数,因为它们不能包含任何实现,构造函数与对象创建有关。


Conclusion

In C#, choosing between abstract classes and interfaces depends on your use case. If you want to provide shared behavior or state, use an abstract class. If you need to enforce a contract across multiple classes that may not be related, use an interface.

结论

在 C# 中,选择抽象类还是接口取决于你的使用场景。如果你想提供共享行为或状态,使用抽象类。如果你需要在可能不相关的多个类中强制执行合同,使用接口。


Would you like additional examples or deeper dives into when to use each one?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *