Menu
CoddyTech

Classes abstratas

Lição 39 de 48 do curso C# para desenvolvedores de R da Coddy.

Uma classe S4 do R declarada com representation("VIRTUAL") não pode ser criada com new(), e um genérico sem método para uma subclasse só falha quando é chamado. As classes e os membros abstratos do C# têm uma função relacionada, mas o compilador os verifica: uma classe concreta que não implementa um override ou usa uma assinatura incorreta não compila. Nenhuma das classes base abstratas deve ser instanciada diretamente.

Uma classe abstrata pode definir uma estrutura compartilhada e exigir comportamento das classes derivadas. Ela não pode ser instanciada diretamente. Métodos abstratos não têm corpo na classe base, e as classes concretas derivadas devem substituí-los. Coleções polimórficas permitem que quem as chama solicite a área sem verificar o tipo de cada classe concreta.

Referência em 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))))

Declarações auxiliares em 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; } }

Instruções em C# dentro de Main

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

Estes são trechos didáticos específicos. Os arquivos do desafio incluem estruturas executáveis completas; os trechos acima mostram as declarações e instruções relevantes.

Saída de referência:

3.0

Saída em C#:

3.0
challenge icon

Desafio

Fácil

Implemente Rectangle e Triangle derivados de Shape abstrata. A área de Rectangle é width * height. A área de Triangle é base * altitude / 2.0. Retorne a soma usando referências a Shape. As dimensões são inteiros não negativos.

Main.cs lê as linhas descritas, chama Exercise.Solve, verifica se a entrada não foi modificada e imprime o resultado com uma quebra de linha final. Mantenha as APIs declaradas. Não adicione um segundo Main nem imprima saída de diagnóstico.

O inicializador bloqueado também testa a API auxiliar ou de classe exportada de forma independente, não apenas o wrapper Solve.

Experimente você mesmo

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 iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de C# para desenvolvedores de R

Pratique por conta própria: Compilador de C# online