Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Abstracción | Principios de POO
C# Más Allá de lo Básico

bookAbstracción

La abstracción es un concepto fundamental en la programación orientada a objetos (OOP) que permite ocultar detalles complejos de implementación y centrarse en las funcionalidades esenciales. En C#, la abstracción se logra mediante clases abstractas.

Note
Nota

La OOP se basaba inicialmente en tres principios (a veces denominados "Los Tres Pilares de la OOP"), que incluyen Encapsulamiento, Herencia y Polimorfismo. Por lo tanto, la Abstracción es una adición reciente y, según algunas fuentes, puede que no se considere un concepto fundamental; sin embargo, es un concepto importante.

Una clase abstracta es una clase que no puede ser instanciada, lo que significa que no se puede crear un objeto de esa clase. Una clase abstracta puede contener atributos y métodos como cualquier otra clase; sin embargo, también puede contener métodos abstractos, que son métodos plantilla destinados a ser implementados por las clases derivadas.

Se puede crear una clase abstracta agregando la palabra clave abstract antes de la definición de la clase. Por ejemplo, vamos a crear una clase abstracta llamada 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 } }

De manera similar, se puede crear un método abstracto agregando la palabra clave abstract antes de su tipo de retorno. Un método abstracto no tiene cuerpo; es simplemente un plano:

index.cs

index.cs

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

El propósito de esto es crear un plano para otras clases. Esto ayuda a simplificar el código. Para comprenderlo mejor, observemos la tarea de Polimorfismo del Capítulo 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()); } }

En el ejemplo anterior, nunca se pretende utilizar la clase Shape, sin embargo, aún era necesario escribir algunas implementaciones ficticias de los métodos getArea y calculatePerimeter dentro de la clase Shape. Se puede simplificar este código haciendo que la clase Shape sea abstracta; además, también se pueden declarar los métodos getArea y calculatePerimeter como abstractos.

Note
Nota

Un método puede ser abstracto o virtual, pero no ambos al mismo tiempo. Sin embargo, es importante señalar que un método abstracto es básicamente un método virtual (sobrescribible), pero no tiene cuerpo en la clase 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. ¿Qué palabra clave se utiliza para hacer una clase abstracta?

2. ¿Se puede instanciar una clase abstracta?

question mark

¿Qué palabra clave se utiliza para hacer una clase abstracta?

Select the correct answer

question mark

¿Se puede instanciar una clase abstracta?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 8

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Awesome!

Completion rate improved to 2.04

bookAbstracción

Desliza para mostrar el menú

La abstracción es un concepto fundamental en la programación orientada a objetos (OOP) que permite ocultar detalles complejos de implementación y centrarse en las funcionalidades esenciales. En C#, la abstracción se logra mediante clases abstractas.

Note
Nota

La OOP se basaba inicialmente en tres principios (a veces denominados "Los Tres Pilares de la OOP"), que incluyen Encapsulamiento, Herencia y Polimorfismo. Por lo tanto, la Abstracción es una adición reciente y, según algunas fuentes, puede que no se considere un concepto fundamental; sin embargo, es un concepto importante.

Una clase abstracta es una clase que no puede ser instanciada, lo que significa que no se puede crear un objeto de esa clase. Una clase abstracta puede contener atributos y métodos como cualquier otra clase; sin embargo, también puede contener métodos abstractos, que son métodos plantilla destinados a ser implementados por las clases derivadas.

Se puede crear una clase abstracta agregando la palabra clave abstract antes de la definición de la clase. Por ejemplo, vamos a crear una clase abstracta llamada 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 } }

De manera similar, se puede crear un método abstracto agregando la palabra clave abstract antes de su tipo de retorno. Un método abstracto no tiene cuerpo; es simplemente un plano:

index.cs

index.cs

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

El propósito de esto es crear un plano para otras clases. Esto ayuda a simplificar el código. Para comprenderlo mejor, observemos la tarea de Polimorfismo del Capítulo 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()); } }

En el ejemplo anterior, nunca se pretende utilizar la clase Shape, sin embargo, aún era necesario escribir algunas implementaciones ficticias de los métodos getArea y calculatePerimeter dentro de la clase Shape. Se puede simplificar este código haciendo que la clase Shape sea abstracta; además, también se pueden declarar los métodos getArea y calculatePerimeter como abstractos.

Note
Nota

Un método puede ser abstracto o virtual, pero no ambos al mismo tiempo. Sin embargo, es importante señalar que un método abstracto es básicamente un método virtual (sobrescribible), pero no tiene cuerpo en la clase 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. ¿Qué palabra clave se utiliza para hacer una clase abstracta?

2. ¿Se puede instanciar una clase abstracta?

question mark

¿Qué palabra clave se utiliza para hacer una clase abstracta?

Select the correct answer

question mark

¿Se puede instanciar una clase abstracta?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 8
some-alt