Overriding (Ghi đè)
Lớp con triển khai hành vi riêng cho phương thức của lớp cha. Dùng abstract và override.
Ví dụ Overriding
using System;
namespace PolymorphismApplication {
abstract class Shape { public abstract int area(); }
class Rectangle : Shape {
private int length, 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();
}
}
}
Method Hiding (Shadowing)
Phương thức lớp cha có sẵn cho lớp con không dùng override. Lớp con có version riêng. Dùng new keyword.
Ví dụ Shadowing
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());
}
}