new与override

new:隐藏了父类的虚拟方法;在内存里面重新分配了内存空间来存放新的方法,所以仍然可以访问父类的方法;

override:重写了父类的虚拟方法;在内存里面使用的是父类方法使用的内存空间.

 

 1 namespace ConsoleApplication3
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             Bird bird = new Chicken();
 8             bird.ShowType();      //output1:Type2 is Chicken
         Console.WriteLine(Chicken.x);       //output: chicken x
              Console.WriteLine(Bird.x);          //output: bird x  仍然可以访问父类的字段
         //demo2
              //Chicken bird = new Chicken();
 8            //bird.ShowType();      //output2:Type2 is Chicken
 9             Console.ReadLine();
10         }
11     }
12 
13 
14     public abstract class Animal
15     {
16         public abstract void ShowType();
17 
18         public void Eat()
19         {
20             Console.WriteLine("Animal always eat.");
21         }
22     }
23 
24     public class Bird : Animal
25     {
           public new static string x = "bird x";
26         private string type = "Bird";
27 
28          public override void ShowType()
29         {
30             Console.WriteLine("Type is {0}",type);
31         }
32 
33         public string color;
34 
35         public string Color
36         {
37             get { return color;}
38             set {color = value;}
39         }
40     }
41 
42     public class Chicken : Bird
43     {
           public new static string x = "chicken x";
44         private string type = "Chicken";
45 
46         public override void ShowType()
47         {
48             Console.WriteLine("Type2 is {0}", type);
49         }
50         public void ShowColor() 
51         {
52             Console.WriteLine("Color is {0}",Color);
53         }
54     }
55 }
56 

 尝试2:

修改:

 

public class Chicken : Bird
    {
        private string type = "Chicken";

        public new void ShowType()
        {
            Console.WriteLine("Type2 is {0}", type);
        }
        public void ShowColor()
        {
            Console.WriteLine("Color is {0}",Color);
        }
    }

 

//output1:Type is Bird

//output2:Type2 is Chicken

尝试2:

 

 

posted @ 2009-12-15 00:06  风影极光  阅读(312)  评论(0编辑  收藏  举报