Created
October 6, 2025 12:51
-
-
Save sunmeat/bb5be0c00999456685eaa3effe18aee4 to your computer and use it in GitHub Desktop.
hiding, shadowing, sealed
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; | |
class BaseClass | |
{ | |
// приховування полів: поле в базовому класі | |
public int field = 10; | |
// статичний метод для приховування | |
public static void StaticMethod() | |
{ | |
Console.WriteLine("статичний метод базового класу"); | |
} | |
} | |
class DerivedClass : BaseClass | |
{ | |
// приховування полів: поле з тим самим ім'ям, але іншим типом (string) | |
public new string field = "приховане поле"; | |
// приховування статичного методу з new | |
public new static void StaticMethod() | |
{ | |
Console.WriteLine("статичний метод похідного класу (приховує базовий)"); | |
} | |
public void ShowShadowing() | |
{ | |
// затінення: локальна змінна з тим самим ім'ям, що й поле класу | |
int field = 42; // затінює поле класу | |
Console.WriteLine("локальна змінна field (затінення): {0}", field); // 42 | |
Console.WriteLine("поле класу field: {0}", this.field); // приховане поле | |
} | |
} | |
sealed class SealedClass | |
{ | |
// запечатаний клас: не можна успадковувати | |
public void Method() | |
{ | |
Console.WriteLine("метод запечатаного класу"); | |
} | |
} | |
// спроба успадкування від sealed - закоментовано, бо помилка компіляції | |
// class InvalidDerived : SealedClass { } | |
class Program | |
{ | |
static void Main() | |
{ | |
Console.OutputEncoding = Encoding.UTF8; | |
Console.WriteLine("демонстрація приховування полів та методів:"); | |
var baseObj = new BaseClass(); | |
var derivedObj = new DerivedClass(); | |
Console.WriteLine("базовий об'єкт: поле = {0}", baseObj.field); // 10 | |
Console.WriteLine("похідний об'єкт: поле = {0}", derivedObj.field); // приховане поле | |
Console.WriteLine("базовий як похідний: поле = {0}", ((BaseClass)derivedObj).field); // 10 (приховане не видно) | |
BaseClass.StaticMethod(); // статичний метод базового класу | |
DerivedClass.StaticMethod(); // статичний метод похідного класу (приховує базовий) | |
Console.WriteLine("\nдемонстрація затінення (shadowing):"); | |
derivedObj.ShowShadowing(); // затінення: локальна змінна field приховує поле класу | |
Console.WriteLine("\nдемонстрація запечатаного класу:"); | |
SealedClass sealedObj = new SealedClass(); | |
sealedObj.Method(); | |
// class Invalid : SealedClass {} // помилка: не можна успадковувати від sealed | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment