Menu
CoddyTech

Clases abstractas

Lección 39 de 48 del curso C# para desarrolladores de R de Coddy.

Una clase R S4 declarada con representation("VIRTUAL") no se puede crear con new(), y un genérico sin un método para una subclase falla solo cuando se lo llama. Las clases y los miembros abstractos de C# cumplen una función relacionada, pero el compilador los comprueba: una clase concreta a la que le falta un override o cuya firma es incorrecta no se compila. Ninguna de las dos clases base abstractas debe instanciarse directamente.

Una clase abstracta puede definir una estructura compartida y exigir un comportamiento derivado. No se puede instanciar directamente. Los métodos abstractos no tienen cuerpo en la clase base, y las clases concretas derivadas deben sobrescribirlos. Las colecciones polimórficas permiten que quienes las llaman soliciten el área sin comprobar el tipo de cada clase concreta.

Referencia de R

setClass("Shape", representation("VIRTUAL"))
invisible(setGeneric("area", function(shape) standardGeneric("area")))
setClass("Triangle", contains = "Shape",
         representation(base = "numeric", height = "numeric"))
setMethod("area", "Triangle", function(shape) shape@base * shape@height / 2)
cat(sprintf("%.1f\n", area(new("Triangle", base = 3, height = 2))))

Declaraciones auxiliares de C#

abstract class Shape { public abstract double Area(); }
class Triangle : Shape { private int b,h; public Triangle(int b,int h) { this.b=b; this.h=h; } public override double Area() { return b*h/2.0; } }

Instrucciones de C# dentro de Main

Shape shape = new Triangle(3, 2);
Console.WriteLine(shape.Area().ToString("0.0", CultureInfo.InvariantCulture));

Estos son fragmentos didácticos centrados en aspectos específicos. Los archivos del desafío incluyen envoltorios ejecutables completos; los fragmentos anteriores muestran las declaraciones y las instrucciones pertinentes.

Salida de referencia:

3.0

Salida de C#:

3.0
challenge icon

Desafío

Fácil

Implementa Rectangle y Triangle derivados de Shape abstracta. El área del rectángulo es width * height. El área del triángulo es base * altitude / 2.0. Devuelve la suma mediante referencias a Shape. Las dimensiones son enteros no negativos.

Edita los archivos C# desbloqueados. El archivo bloqueado visible Main.cs lee las líneas descritas, llama a Exercise.Solve, verifica que la entrada no se haya modificado e imprime el resultado con un único salto de línea final. Mantén las API declaradas. No añadas un segundo Main ni imprimas mensajes de diagnóstico.

El lanzador bloqueado también prueba la API de la clase o del asistente exportado de forma independiente, no solo el contenedor Solve.

Pruébalo tú mismo

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var a2 = I(input[2]); string before2=Snapshot(a2);
var a3 = I(input[3]); string before3=Snapshot(a3);
Shape sh1 = new Rectangle(2,3); Shape sh2 = new Triangle(1,1); if (sh1.Area() != 6 || sh2.Area() != 0.5) throw new Exception("Shape API");
var result = Exercise.Solve(a0,a1,a2,a3);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
if (Snapshot(a2) != before2) throw new Exception("Input mutation");
if (Snapshot(a3) != before3) throw new Exception("Input mutation");
Console.WriteLine(result.ToString("0.0", CultureInfo.InvariantCulture));
}
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de C# para desarrolladores de R

Practica por tu cuenta: Compilador de C# online