Last active
January 23, 2026 10:00
-
-
Save sunmeat/5bf7729a0887cde7f1955b2d8585e84e to your computer and use it in GitHub Desktop.
inheritance problems
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Text; | |
| namespace DuckExample | |
| { | |
| // абстрактна качка | |
| internal abstract class Duck | |
| { | |
| public virtual void Quack() | |
| { | |
| Console.WriteLine("качка крякає!"); | |
| } | |
| public virtual void Swim() | |
| { | |
| Console.WriteLine("качка плаває!"); | |
| } | |
| public virtual void Fly() | |
| { | |
| Console.WriteLine("качка літає!"); | |
| } | |
| // абстрактний метод — кожна качка виглядає по-своєму | |
| public abstract void Display(); | |
| } | |
| // крижнева качка | |
| internal class MallardDuck : Duck | |
| { | |
| public override void Display() | |
| { | |
| Console.WriteLine("https://www.ndow.org/wp-content/uploads/2021/10/anas_platyrhynchos.jpg"); | |
| } | |
| } | |
| // червоношия качка | |
| internal class RedheadDuck : Duck | |
| { | |
| public override void Display() | |
| { | |
| Console.WriteLine("https://www.ducks.org/files/live/sites/ducksorg/files/Waterfowl%20ID/Diving%20Ducks/Redhead/Redhead%20drake.jpg"); | |
| } | |
| } | |
| // гумова качка | |
| internal class RubberDuck : Duck | |
| { | |
| public override void Display() | |
| { | |
| Console.WriteLine("https://asiantigersgroup.com/wp-content/uploads/2023/06/AT-Duck-1.jpeg"); | |
| } | |
| public override void Fly() | |
| { | |
| Console.WriteLine("ОЙ! гумова качка не літає!!!"); | |
| throw new Exception(); | |
| } | |
| } | |
| internal static class Program | |
| { | |
| // генератор качок | |
| private static Duck GetSomeDuck() | |
| { | |
| return Random.Shared.Next(2) == 0 ? new RedheadDuck() : new MallardDuck(); | |
| } | |
| private static void Main() | |
| { | |
| Console.OutputEncoding = Encoding.UTF8; | |
| Console.WriteLine("Спадкування - це не завжди добре!"); | |
| Duck duck = GetSomeDuck(); | |
| duck.Quack(); | |
| duck.Swim(); | |
| duck.Fly(); | |
| duck.Display(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment