C# 中的覆盖与遮盖
覆盖
在覆盖过程中,你可以定义专属于子类类型的一种行为,这意味着子类可以根据其需求来实施父类方法。
让我们来看一下实现覆盖的抽象类的示例 −
示例
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();
}
}
}遮盖
遮盖也称为方法隐藏。在遮盖中,父类的方法可以使用于子类,而不使用 override 关键字。子类有其自己的版本,具有同样的功能。
使用 new 关键字进行遮盖,创建基本类函数的自己的版本。
让我们来看一个示例 −
示例
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());
}
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP