Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Astrazione | Principi OOP
C# Oltre le Basi

bookAstrazione

L'astrazione è un concetto fondamentale nella programmazione orientata agli oggetti (OOP) che consente di nascondere i dettagli complessi dell'implementazione e di concentrarsi sulle funzionalità essenziali. In C#, l'astrazione viene realizzata tramite le classi astratte.

Note
Nota

L'OOP si basava inizialmente su tre principi (talvolta chiamati "I Tre Pilastri dell'OOP"), tra cui Incapsulamento, Ereditarietà e Polimorfismo. Pertanto, l'Astrazione è una nuova aggiunta e talvolta potrebbe non essere considerata un concetto fondamentale secondo alcune fonti; tuttavia, rappresenta comunque un concetto importante.

Una classe astratta è una classe che non può essere istanziata, il che significa che non è possibile creare un oggetto di quella classe. Una classe astratta può contenere attributi e metodi come qualsiasi altra classe, ma può anche includere metodi astratti, che sono metodi modello destinati a essere implementati dalle classi derivate.

È possibile creare una classe astratta aggiungendo la parola chiave abstract prima della definizione della classe. Ad esempio, creiamo una classe astratta chiamata Shape:

index.cs

index.cs

copy
12345678910111213141516171819
using 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 } }

Allo stesso modo, è possibile creare un metodo astratto aggiungendo la parola chiave abstract prima del suo tipo di ritorno. Un metodo astratto non ha alcun corpo: rappresenta semplicemente uno schema:

index.cs

index.cs

copy
1234567891011
abstract class Shape { protected float circumference; public float getCircumference() { return circumference; } public abstract float getArea(); }

Lo scopo di questo è creare un modello per altre classi. Questo aiuta a semplificare il codice. Per comprendere meglio, osserviamo l'esercizio sulla Polimorfismo dal Capitolo 5:

index.cs

index.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
using 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()); } }

Nell'esempio sopra, non si intende mai utilizzare la classe Shape, tuttavia è stato comunque necessario scrivere alcune implementazioni fittizie dei metodi getArea e calculatePerimeter all'interno della classe Shape. È possibile semplificare questo codice rendendo la classe Shape astratta; inoltre, è possibile rendere astratti anche i metodi getArea e calculatePerimeter.

Note
Nota

Un metodo può essere astratto oppure virtuale, ma non entrambi contemporaneamente. Tuttavia, è importante notare che un metodo astratto è fondamentalmente un metodo virtuale (sovrascrivibile), ma non possiede alcun corpo nella classe base.

index.cs

index.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
using 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. Quale parola chiave viene utilizzata per rendere una classe astratta?

2. Una classe astratta può essere istanziata?

question mark

Quale parola chiave viene utilizzata per rendere una classe astratta?

Select the correct answer

question mark

Una classe astratta può essere istanziata?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 5. Capitolo 8

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Suggested prompts:

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

bookAstrazione

Scorri per mostrare il menu

L'astrazione è un concetto fondamentale nella programmazione orientata agli oggetti (OOP) che consente di nascondere i dettagli complessi dell'implementazione e di concentrarsi sulle funzionalità essenziali. In C#, l'astrazione viene realizzata tramite le classi astratte.

Note
Nota

L'OOP si basava inizialmente su tre principi (talvolta chiamati "I Tre Pilastri dell'OOP"), tra cui Incapsulamento, Ereditarietà e Polimorfismo. Pertanto, l'Astrazione è una nuova aggiunta e talvolta potrebbe non essere considerata un concetto fondamentale secondo alcune fonti; tuttavia, rappresenta comunque un concetto importante.

Una classe astratta è una classe che non può essere istanziata, il che significa che non è possibile creare un oggetto di quella classe. Una classe astratta può contenere attributi e metodi come qualsiasi altra classe, ma può anche includere metodi astratti, che sono metodi modello destinati a essere implementati dalle classi derivate.

È possibile creare una classe astratta aggiungendo la parola chiave abstract prima della definizione della classe. Ad esempio, creiamo una classe astratta chiamata Shape:

index.cs

index.cs

copy
12345678910111213141516171819
using 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 } }

Allo stesso modo, è possibile creare un metodo astratto aggiungendo la parola chiave abstract prima del suo tipo di ritorno. Un metodo astratto non ha alcun corpo: rappresenta semplicemente uno schema:

index.cs

index.cs

copy
1234567891011
abstract class Shape { protected float circumference; public float getCircumference() { return circumference; } public abstract float getArea(); }

Lo scopo di questo è creare un modello per altre classi. Questo aiuta a semplificare il codice. Per comprendere meglio, osserviamo l'esercizio sulla Polimorfismo dal Capitolo 5:

index.cs

index.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
using 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()); } }

Nell'esempio sopra, non si intende mai utilizzare la classe Shape, tuttavia è stato comunque necessario scrivere alcune implementazioni fittizie dei metodi getArea e calculatePerimeter all'interno della classe Shape. È possibile semplificare questo codice rendendo la classe Shape astratta; inoltre, è possibile rendere astratti anche i metodi getArea e calculatePerimeter.

Note
Nota

Un metodo può essere astratto oppure virtuale, ma non entrambi contemporaneamente. Tuttavia, è importante notare che un metodo astratto è fondamentalmente un metodo virtuale (sovrascrivibile), ma non possiede alcun corpo nella classe base.

index.cs

index.cs

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
using 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. Quale parola chiave viene utilizzata per rendere una classe astratta?

2. Una classe astratta può essere istanziata?

question mark

Quale parola chiave viene utilizzata per rendere una classe astratta?

Select the correct answer

question mark

Una classe astratta può essere istanziata?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 5. Capitolo 8
some-alt