การเอาชนะ
ภายใต้การแทนที่ คุณสามารถกำหนดลักษณะการทำงานเฉพาะสำหรับประเภทคลาสย่อย ซึ่งหมายความว่าคลาสย่อยสามารถใช้เมธอดคลาสพาเรนต์ตามความต้องการได้
ให้เราดูตัวอย่างของคลาสนามธรรมที่ใช้การเอาชนะ -
ตัวอย่าง
using System;
namespace PolymorphismApplication {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
} การแรเงา
การแรเงาเรียกอีกอย่างว่าการซ่อนวิธีการ เมธอดของคลาสพาเรนต์ใช้ได้กับคลาสย่อยโดยไม่ต้องใช้คีย์เวิร์ดแทนที่ในแชโดว์ คลาสย่อยมีฟังก์ชันเดียวกันในเวอร์ชันของตัวเอง
ใช้คีย์เวิร์ดใหม่เพื่อดำเนินการแชโดว์และสร้างเวอร์ชันของฟังก์ชันคลาสพื้นฐานเอง
เรามาดูตัวอย่างกัน −
ตัวอย่าง
using System;
using System.Collections.Generic;
class Demo {
public class Parent {
public string Display() {
return "Parent Class!";
}
}
public class Child : Parent {
public new string Display() {
return "Child Class!";
}
}
static void Main(String[] args) {
Child child = new Child();
Console.WriteLine(child.Display());
}
}