Sobes.tech
Junior

What is abstraction in programming?

sobes.tech AI

Answer from AI

Abstraction is a mechanism that allows hiding implementation details and providing a generalized view of a system or its components. It focuses on "what" an object does, rather than "how" it does it.

In C#, abstraction is implemented through:

  • Abstract classes: Can contain abstract methods (without implementation) and regular members. An instance of an abstract class cannot be created.
    // Abstract class with an abstract method
    public abstract class Shape
    {
        public abstract double GetArea(); // Abstract method
        public string Name { get; set; }
    
        public void DisplayInfo() // Regular method
        {
            Console.WriteLine($"Shape: {Name}");
        }
    }
    
  • Interfaces: Define a contract that a class must implement. They contain only method, property, event, and indexer declarations (before C# 8), or can contain default implementations (from C# 8).
    // Interface
    public interface IDrawable
    {
        void Draw(); // Method without implementation
    }
    

Principles of abstraction:

  • Encapsulation: Binding data and methods that operate on that data into a single unit. It promotes hiding internal structure.
  • Inheritance: Allows creating new classes based on existing ones, inheriting their properties and methods, while adding or overriding functionality.

Application of abstraction:

  • Simplifying complex systems.
  • Increasing code flexibility.
  • Improving maintainability.
  • Creating reusable components.
What is abstraction in programming? — C# - sobes.tech