類的運用,求矩形面積,運用矩形面積
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Test09
7 {
8 //class MyClass1
9 //{
10 // private int width = 0; //定義int型變量,作為矩形的長
11 // private int height = 0; //定義int型變量,作為矩形的寬
12 // /// <summary>
13 // /// 長
14 // /// </summary>
15 // public int Width
16 // {
17 // get
18 // {
19 // return width;
20 // }
21 // set
22 // {
23 // width = value;
24 // }
25 // }
26 // /// <summary>
27 // /// 寬
28 // /// </summary>
29 // public int Height
30 // {
31 // get
32 // {
33 // return height;
34 // }
35 // set
36 // {
37 // height = value;
38 // }
39 // }
40 //}
41 ///// <summary>
42 ///// 自定義類,該類繼承自MyClass1
43 ///// </summary>
44 //class MyClass2 : MyClass1
45 //{
46 // /// <summary>
47 // /// 求矩形的面積
48 // /// </summary>
49 // /// <returns>矩形的面積</returns>
50 // public int Area()
51 // {
52 // return Width * Height;
53 // }
54 //}
55 //class Program
56 //{
57 // static void Main(string[] args)
58 // {
59 // MyClass2 myClass2 = new MyClass2();
60 // myClass2.Width = 5;
61 // myClass2.Height = 3;
62 // Console.WriteLine("矩形的面積為:" + myClass2.Area());
63 // }
64 //}
65 class Class1
66 {
67 private int width=0;//聲明私有
68 private int height=0;
69 public int Width//公有
70 {
71 get
72 {
73 return width;
74 }
75 set
76 {
77 width = value;
78 }
79 }
80 public int Height
81 {
82 get
83 {
84 return height;
85 }
86 set
87 {
88 height = value;
89 }
90 }
91 }
92 class Class2 : Class1
93 {
94 public int Area()
95 {
96
97 return Width * Height;//與讀寫的變量名保持一致,且大寫對外,小寫對內
98 }
99
100 }
101 class Program //Program名稱任意,符合命名規則即可
102 {
103 static void Main(string[] args)
104 {
105 Class2 class2 = new Class2();//實例化對象
106 //Class1.Width=1;
107 //Class1.Height=1;
108 class2.Width=1; //通過子類進行賦值,而不是父類
109 class2.Height = 1; //大寫對外,小寫對內,由Class1可知
110 Console.WriteLine(class2.Area());
111
112 }
113 }
114
115 }