C # -- upward Transformation

Source: Internet
Author: User

In the process of learning C #, some basic knowledge, such as data types, control structures, arrays, and so on, are similar to the previous languages, and can be understood, however, the concept of upward transformation was first encountered.

After learning about it, I will roughly understand it as follows:

An upward transformation is to transform a subclass into a parent class, and an object can be used as its own type.

Let's take a look at a piece of code:

Public class Animal {public virtual void Eat () {Console. WriteLine ("I am an Animal, I want to Eat! ") ;}} Public class Bird: Animal {public override void Eat () {Console. WriteLine (" I'm a Bird, I want to Eat! ") ;}} Class Test {static void Main (string [] args) {Animal animal = new Bird (); // converts animal. Eat ();}}

In the above example, we define an animal class (where there is a way to eat), birds inherit the animal class (override the methods to eat in the base class ), the animal in the main function is an Animal type object, but the running result is not what we expected, but shows "I am a bird, I want to eat! ".

For this example. When animal is declared, the animal type is Animal. However, animal points to an Animal subclass, that is, Bird.

Of course, if there is an upward transformation, there will be a downward transformation, of course, the opposite way, that is, converting the parent class into a subclass.

When I see a problem on the Internet, some people say, "If the functions required by the subclass exist in the parent class, use the upward transformation. If the features required by the parent class exist in the subclass, "downward transformation is used," but as described above, Bird is a subclass of Animal. Bird has inherited the methods in Animal. Why do we need to use downward transformation? That is, why should we use "Animal = new Bird ();" instead of "Bird animal = new Bird ();" when defining animal?

Ask your friends to give us some comments and suggestions.

Related Article

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.