在覆盖下,您可以定义特定于子类类型的行为,这意味着子类可以根据其要求实现父类方法。
让我们看一个实现Overriding的抽象类的示例-
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("矩形类区域:");
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();
}
}
}阴影也称为方法隐藏。父类的方法可用于子类,而无需在阴影中使用override关键字。子类具有相同功能的自己的版本。
使用new关键字执行阴影处理并创建自己的基类函数版本。
让我们看一个例子-
using System;
using System.Collections.Generic;
class Demo {
public class Parent {
public string Display() {
return "家长班!";
}
}
public class Child : Parent {
public new string Display() {
return "儿童班!";
}
}
static void Main(String[] args) {
Child child = new Child();
Console.WriteLine(child.Display());
}
}