What is abstraction in C#?

WBOY
Release: 2023-08-29 22:41:05
forward
634 people have browsed it

C# 中的抽象是什么?

Abstraction and encapsulation are relevant features in object-oriented programming. Abstraction allows making relevant information visible, while encapsulation enables the programmer to achieve the desired level of abstraction.

Abstraction can be achieved using abstract classes in C#. C# allows you to create abstract classes that provide partial class implementations of interfaces. When a derived class inherits it, the implementation is complete. Abstract classes contain abstract methods, which are implemented by derived classes. Derived classes have more specialized functionality.

Here are some key points-

  • You cannot create an instance of an abstract class

  • Cannot be declared outside an abstract class Abstract method

  • When a class is declared sealed, it cannot be inherited, and abstract classes cannot be declared sealed.

Example

Real-time demonstration

using System;
namespace Demo {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }
      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * length);
      }
   }
   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(20, 15);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}
Copy after login

Output

Rectangle class area :
Area: 300
Copy after login

The above is the detailed content of What is abstraction in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template