Advertisement
ArcaniSGK507

Untitled

Feb 1st, 2025
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.90 KB | None | 0 0
  1. using System;
  2.  
  3. // Clase base
  4. class Animal
  5. {
  6.     protected string Nombre;
  7.  
  8.     public Animal(string nombre)
  9.     {
  10.         Nombre = nombre;
  11.     }
  12.  
  13.     public virtual void HacerSonido()
  14.     {
  15.         Console.WriteLine("El animal hace un sonido.");
  16.     }
  17. }
  18.  
  19. // Clase derivada (herencia)
  20. class Perro : Animal
  21. {
  22.     public Perro(string nombre) : base(nombre) { }
  23.  
  24.     public override void HacerSonido() // Polimorfismo
  25.     {
  26.         Console.WriteLine($"{Nombre} dice: ¡Guau!");
  27.     }
  28. }
  29.  
  30. class Gato : Animal
  31. {
  32.     public Gato(string nombre) : base(nombre) { }
  33.  
  34.     public override void HacerSonido()
  35.     {
  36.         Console.WriteLine($"{Nombre} dice: ¡Miau!");
  37.     }
  38. }
  39.  
  40. class Program
  41. {
  42.     static void Main()
  43.     {
  44.         Animal miPerro = new Perro("Firulais");
  45.         Animal miGato = new Gato("Mishi");
  46.  
  47.         miPerro.HacerSonido();
  48.         miGato.HacerSonido();
  49.     }
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement