C # Allow the methods in the derived class to have the same signature as those in the base class: Use the keyword virtual to define the virtual method in the base class, and then use the keyword override in the derived class to override the method, or use the keyword new to overwrite the method (hide the method ).
The rewrite method uses the same signature to override the inherited virtual method. Declaration is used, while declaration is used to make existing)
By default, the C # method is non-virtual ., Rewriting non-virtual methods will cause compilation errors.
In addition to class methods, you can also use other class members with the virtual keyword to define virtual members, including the attribute [No parameter attribute], the indexer [including parameter attributes], or the event declaration. The Implementation of Virtual members can be rewritten using the keyword override in the derived class, or overwritten using the keyword new.
1: namespace ConsoleApplication2
2: {
3:
4:
5:
6: public class Dimensions
7: {
8:
9: public const double PI = Math.PI;
10: protected double x, y;
11: public Dimensions()
12: {
13:
14: }
15:
16: public Dimensions(double x, double y)
17: {
18: this.x = x;
19: this.y = y;
20: }
21:
22: public virtual double Area()
23: {
24: return x * y;
25: }
26:
27: }
28:
29: public class Circle: Dimensions // derived class: Circle
30: {
31: public Circle(double r)
32: : base(r, 0)
33: {
34:
35: }
36:
37: public override double Area()
38: {
39: // garden area
40: return PI * x * x;
41: }
42: }
43: public class Sphere: Dimensions // derived class: Sphere
44: {
45: public Sphere(double r)
46: : base(r, 0)
47: {
48:
49: }
50:
51: public override double Area()
52: {
53: // sphere surface area
54: return 4 * PI * x * x;
55: }
56: }
57: public class Cylinder: Dimensions // derived class: Cylinder
58: {
59: public Cylinder(double r)
60: : base(r, 0)
61: {
62:
63: }
64:
65: public override double Area()
66: {
67: // surface area of the cylinder
68: return 2 * PI * x * x + 2 * PI * x * y;
69: }
70: }
71:
72: public class Program
73: {
74:
75:
76: static void Main(string[] args)
77: {
78: double r = 3.0, h = 5.0;
79: Dimensions c = new Circle (r); // Circle
80:
81: Dimensions s = new Sphere (r); // Sphere
82:
83:
84: Dimensions l = new Cylinder (r); // Cylinder
85:
86: // display the surface area of different shapes
87:
88: Console. WriteLine ("Area of the Circle = {0: f2}", c. Area ());
89: Console. WriteLine ("Sphere Area = {0: f2}", s. Area ());
90: Console. WriteLine ("cylindrical Area = {0: f2}", l. Area ());
91: Console.ReadKey();
92: }
93: }
94: }