使用类来继承接口

时间:2022-07-29 19:27:22

如public class Car : MotorVehicle, IDrivable, ISteerable形式,例如:

  
  
  
1 /*
2 Example8_3.cs illustrates inheriting from a class and
3 implementing multiple interfaces
4   */
5
6 using System;
7
8
9 public interface IDrivable
10 {
11
12 // method declarations
13 void Start();
14 void Stop();
15
16 // property declaration
17 bool Started
18 {
19 get ;
20 }
21
22 }
23
24
25 public interface ISteerable
26 {
27
28 // method declarations
29 void TurnLeft();
30 void TurnRight();
31
32 }
33
34
35 public class MotorVehicle
36 {
37
38 // declare the field
39 private string model;
40
41 // define a constructor
42 public MotorVehicle( string model)
43 {
44 this .model = model;
45 }
46
47 // declare a property
48 public string Model
49 {
50 get
51 {
52 return model;
53 }
54 set
55 {
56 model = value;
57 }
58 }
59
60 }
61
62
63 // Car class inherits from the MotorVehicle class and
64 // implements the IDrivable and ISteerable interfaces
65 public class Car : MotorVehicle, IDrivable, ISteerable
66 {
67
68 // declare the underlying field used by the
69 // Started property of the IDrivable interface
70 private bool started = false ;
71
72 // define a constructor
73 public Car( string model) :
74 base (model) // calls the base class constructor
75 {
76 // do nothing
77 }
78
79 // implement the Start() method of the IDrivable interface
80 public void Start()
81 {
82 Console.WriteLine( " car started " );
83 started = true ;
84 }
85
86 // implement the Stop() methodof the IDrivable interface
87 public void Stop()
88 {
89 Console.WriteLine( " car stopped " );
90 started = false ;
91 }
92
93 // implement the Started property of the IDrivable interface
94 public bool Started
95 {
96 get
97 {
98 return started;
99 }
100 }
101
102 // implement the TurnLeft() method of the ISteerable interface
103 public void TurnLeft()
104 {
105 Console.WriteLine( " car turning left " );
106 }
107
108 // implement the TurnRight() method of the ISteerable interface
109 public void TurnRight()
110 {
111 Console.WriteLine( " car turning right " );
112 }
113
114 }
115
116
117 class Example8_3
118 {
119
120 public static void Main()
121 {
122
123 // create a Car object
124 Car myCar = new Car( " MR2 " );
125
126 Console.WriteLine( " myCar.Model = " + myCar.Model);
127
128 // call myCar.Start()
129 Console.WriteLine( " Calling myCar.Start() " );
130 myCar.Start();
131
132 // call myCar.TurnLeft()
133 Console.WriteLine( " Calling myCar.TurnLeft() " );
134 myCar.TurnLeft();
135
136 }
137
138 }