类与实例

对于我们编程初学者来说,面向对象的三大特征(封装、继承和多态)是必须要了解的,同时我们也要搞清楚类与对象的关系。首先,我们看下类和对象是如何定义的,以及什么实例化。

【Class】类是具有相同的属性和功能的对象的抽象的集合。

【Object】对象是类的实例化。

Instantiation】实例化就是创建对象的过程,一般来说我们使用new关键字来创建。

我们在vs2010中创建一个简单的控制台程序,新建一个Cat类,假设这个Cat有身高,体重,年龄,性别等属性,此外这只Cat还会唱歌。

新建一个Cat类,代码如下:

 1   class Cat
 2     {
 3         private int height;
 4         private int weight;
 5         private int age;
 6         private string gender;
 7 
 8         public int Height
 9         {
10             get { return height; }
11             set { height = value; }
12         }
13        
14         public int Weight
15         {
16             get { return weight; }
17             set { weight = value; }
18         }
19 
20         public int Age
21         {
22             get { return age; }
23             set { age = value; }
24         }
25      
26         public string Gender
27         {
28             get { return gender; }
29             set { gender = value; }
30         }
31         /// <summary>
32         /// Declare a method for sing 
33         /// </summary>
34         /// <param name="song"></param>
35         public void Sing(string song)
36         {
37             Console.WriteLine(song);
38         }
39     }
View Code

 

在main函数中实例化该类:

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5 
 6             Cat cat = new Cat();//instanialize the Cat class
 7             cat.Gender = "Female";
 8             cat.Age = 2;
 9             cat.Height = 10;
10             cat.Weight = 20;
11             Console.WriteLine("this cat is a {0}, she is {1} years old this year,"
12                                 +"now she is {2}cm high and about {3}kg",
13                 cat.Gender, cat.Age, cat.Height, cat.Weight);
14             cat.Sing("Listening, I am sing a song...");//call the Sing method
15             Console.ReadLine();
16         }
17     }
View Code

 

我们可以查看运行的结果:

这是一个很简单的例子,目的为了帮助初学者理解实例化类的基础,当然了这也是我的初学笔记,希望与读者共同进步,每天进步一点点。

 

posted on 2015-10-11 17:55  北纬33点3度  阅读(634)  评论(0编辑  收藏  举报