Абстракція
Абстракція — це фундаментальна концепція об'єктно-орієнтованого програмування (ООП), яка дозволяє приховувати складні деталі реалізації та зосереджуватися на основних функціональних можливостях. У C# абстракція реалізується за допомогою абстрактних класів.
ООП спочатку базувалося на трьох принципах (іноді їх називають «Три стовпи ООП»): інкапсуляція, наслідування та поліморфізм. Тому абстракція є новим доповненням і, згідно з деякими джерелами, іноді не вважається фундаментальною концепцією, проте вона є важливою складовою.
Абстрактний клас — це клас, який не можна створити як об'єкт, тобто не можна створити екземпляр цього класу. Абстрактний клас може містити атрибути та методи, як і будь-який інший клас, але також може містити абстрактні методи, які є методами-шаблонами, призначеними для реалізації у похідних класах.
Створити абстрактний клас можна, додавши ключове слово abstract
перед визначенням класу. Наприклад, створимо абстрактний клас з назвою Shape
:
index.cs
12345678910111213141516171819using System; abstract class Shape { protected float circumference; public float getCircumference() { return circumference; } } class ConsoleApp { static void Main() { Shape s = new Shape(); // Error: Cannot create an instance of an abstract class } }
Аналогічно, можна створити абстрактний метод, додавши ключове слово abstract
перед його типом повернення. Абстрактний метод не має тіла — це лише шаблон:
index.cs
1234567891011abstract class Shape { protected float circumference; public float getCircumference() { return circumference; } public abstract float getArea(); }
Мета цього полягає у створенні шаблону для інших класів. Це допомагає спростити код. Щоб краще це зрозуміти, розглянемо завдання з Поліморфізму з Розділу 5:
index.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102using System; class Shape { // Perimeter is the length of the 'outline' of a shape protected float perimeter; public float getPerimeter() { return perimeter; } public virtual float getArea() { return 0.0f; } // A virtual method can only be either 'public' or 'protected' protected virtual float calculatorPerimeter() { return 0.0f; } } class Rectangle : Shape { float width; float height; public Rectangle(float width, float height) { this.width = width; this.height = height; this.perimeter = getPerimeter(); } public override float getArea() { return width * height; } protected override float calculatorPerimeter() { return width * 2 + height * 2; } } class Square : Shape { float length; public Square(float length) { this.length = length * length; } public override float getArea() { return length * length; } protected override float calculatorPerimeter() { return 4 * length; } } class Circle : Shape { float radius; public Circle(float radius) { this.radius = radius; } // Area of a Circle = pi . r . r public override float getArea() { return 3.14f * radius * radius; } // Perimeter (or) Circumference: 2 . pi . r protected override float calculatorPerimeter() { return 2.00f * 3.14f * radius; } } class ConsoleApp { static void Main() { Rectangle r1 = new Rectangle(10f, 20f); Square s1 = new Square(10f); Circle c1 = new Circle(10f); Console.WriteLine(r1.getArea()); Console.WriteLine(s1.getArea()); Console.WriteLine(c1.getArea()); } }
У наведеному вище прикладі ви ніколи не плануєте використовувати клас Shape
, однак вам все одно довелося написати фіктивні реалізації методів getArea
та calculatePerimeter
у класі Shape
. Ви можете дещо спростити цей код, зробивши клас Shape
абстрактним, а також зробити методи getArea
та calculatePerimeter
абстрактними.
Метод може бути або абстрактним, або віртуальним, але не обома одночасно. Важливо зазначити, що абстрактний метод по суті є віртуальним (таким, що може бути перевизначений), але не має тіла у базовому класі.
index.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100using System; using System.Collections.Generic; abstract class Shape { // Perimeter is the length of the 'outline' of a shape protected float perimeter; public float getPerimeter() { return perimeter; } public abstract float getArea(); protected abstract float calculatorPerimeter(); } class Rectangle : Shape { float width; float height; public Rectangle(float width, float height) { this.width = width; this.height = height; this.perimeter = getPerimeter(); } public override float getArea() { return width * height; } protected override float calculatorPerimeter() { return width * 2 + height * 2; } } class Square : Shape { float length; public Square(float length) { this.length = length * length; } public override float getArea() { return length * length; } protected override float calculatorPerimeter() { return 4 * length; } } class Circle : Shape { float radius; public Circle(float radius) { this.radius = radius; } public override float getArea() { return 3.14f * radius * radius; } protected override float calculatorPerimeter() { return 2.00f * 3.14f * radius; } } class ConsoleApp { static void Main() { Rectangle r1 = new Rectangle(10f, 20f); Square s1 = new Square(10f); Circle c1 = new Circle(10f); // We cannot create an instance of 'Shape' but we can use type datatype "Shape" for creating variables, arrays or lists List<Shape> shapes = new List<Shape>(); shapes.Add(r1); shapes.Add(s1); shapes.Add(c1); foreach(Shape shape in shapes) { Console.WriteLine(shape.getArea()); } } }
1. Яке ключове слово використовується для створення абстрактного класу?
2. Чи можна створити екземпляр абстрактного класу?
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you show me an example of an abstract class with abstract methods in C#?
What is the difference between an abstract class and an interface in C#?
How do derived classes implement abstract methods?
Awesome!
Completion rate improved to 2.04
Абстракція
Свайпніть щоб показати меню
Абстракція — це фундаментальна концепція об'єктно-орієнтованого програмування (ООП), яка дозволяє приховувати складні деталі реалізації та зосереджуватися на основних функціональних можливостях. У C# абстракція реалізується за допомогою абстрактних класів.
ООП спочатку базувалося на трьох принципах (іноді їх називають «Три стовпи ООП»): інкапсуляція, наслідування та поліморфізм. Тому абстракція є новим доповненням і, згідно з деякими джерелами, іноді не вважається фундаментальною концепцією, проте вона є важливою складовою.
Абстрактний клас — це клас, який не можна створити як об'єкт, тобто не можна створити екземпляр цього класу. Абстрактний клас може містити атрибути та методи, як і будь-який інший клас, але також може містити абстрактні методи, які є методами-шаблонами, призначеними для реалізації у похідних класах.
Створити абстрактний клас можна, додавши ключове слово abstract
перед визначенням класу. Наприклад, створимо абстрактний клас з назвою Shape
:
index.cs
12345678910111213141516171819using System; abstract class Shape { protected float circumference; public float getCircumference() { return circumference; } } class ConsoleApp { static void Main() { Shape s = new Shape(); // Error: Cannot create an instance of an abstract class } }
Аналогічно, можна створити абстрактний метод, додавши ключове слово abstract
перед його типом повернення. Абстрактний метод не має тіла — це лише шаблон:
index.cs
1234567891011abstract class Shape { protected float circumference; public float getCircumference() { return circumference; } public abstract float getArea(); }
Мета цього полягає у створенні шаблону для інших класів. Це допомагає спростити код. Щоб краще це зрозуміти, розглянемо завдання з Поліморфізму з Розділу 5:
index.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102using System; class Shape { // Perimeter is the length of the 'outline' of a shape protected float perimeter; public float getPerimeter() { return perimeter; } public virtual float getArea() { return 0.0f; } // A virtual method can only be either 'public' or 'protected' protected virtual float calculatorPerimeter() { return 0.0f; } } class Rectangle : Shape { float width; float height; public Rectangle(float width, float height) { this.width = width; this.height = height; this.perimeter = getPerimeter(); } public override float getArea() { return width * height; } protected override float calculatorPerimeter() { return width * 2 + height * 2; } } class Square : Shape { float length; public Square(float length) { this.length = length * length; } public override float getArea() { return length * length; } protected override float calculatorPerimeter() { return 4 * length; } } class Circle : Shape { float radius; public Circle(float radius) { this.radius = radius; } // Area of a Circle = pi . r . r public override float getArea() { return 3.14f * radius * radius; } // Perimeter (or) Circumference: 2 . pi . r protected override float calculatorPerimeter() { return 2.00f * 3.14f * radius; } } class ConsoleApp { static void Main() { Rectangle r1 = new Rectangle(10f, 20f); Square s1 = new Square(10f); Circle c1 = new Circle(10f); Console.WriteLine(r1.getArea()); Console.WriteLine(s1.getArea()); Console.WriteLine(c1.getArea()); } }
У наведеному вище прикладі ви ніколи не плануєте використовувати клас Shape
, однак вам все одно довелося написати фіктивні реалізації методів getArea
та calculatePerimeter
у класі Shape
. Ви можете дещо спростити цей код, зробивши клас Shape
абстрактним, а також зробити методи getArea
та calculatePerimeter
абстрактними.
Метод може бути або абстрактним, або віртуальним, але не обома одночасно. Важливо зазначити, що абстрактний метод по суті є віртуальним (таким, що може бути перевизначений), але не має тіла у базовому класі.
index.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100using System; using System.Collections.Generic; abstract class Shape { // Perimeter is the length of the 'outline' of a shape protected float perimeter; public float getPerimeter() { return perimeter; } public abstract float getArea(); protected abstract float calculatorPerimeter(); } class Rectangle : Shape { float width; float height; public Rectangle(float width, float height) { this.width = width; this.height = height; this.perimeter = getPerimeter(); } public override float getArea() { return width * height; } protected override float calculatorPerimeter() { return width * 2 + height * 2; } } class Square : Shape { float length; public Square(float length) { this.length = length * length; } public override float getArea() { return length * length; } protected override float calculatorPerimeter() { return 4 * length; } } class Circle : Shape { float radius; public Circle(float radius) { this.radius = radius; } public override float getArea() { return 3.14f * radius * radius; } protected override float calculatorPerimeter() { return 2.00f * 3.14f * radius; } } class ConsoleApp { static void Main() { Rectangle r1 = new Rectangle(10f, 20f); Square s1 = new Square(10f); Circle c1 = new Circle(10f); // We cannot create an instance of 'Shape' but we can use type datatype "Shape" for creating variables, arrays or lists List<Shape> shapes = new List<Shape>(); shapes.Add(r1); shapes.Add(s1); shapes.Add(c1); foreach(Shape shape in shapes) { Console.WriteLine(shape.getArea()); } } }
1. Яке ключове слово використовується для створення абстрактного класу?
2. Чи можна створити екземпляр абстрактного класу?
Дякуємо за ваш відгук!