New and override

Source: Internet
Author: User

New: hides the virtual method of the parent class; allocates memory space in the memory to store new methods, so you can still access the method of the parent class;

Override: overwrites the virtual method of the parent class. In the memory, the memory space used by the parent class method is used.

 

1 namespace leleapplication3
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 can still access the parent class field // 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

Try 2:

Modify:

 

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

Try 2:

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.