Small example Analysis C # inheritance mechanism

Source: Internet
Author: User

usingSystem;classtest{ Public classA { Public Virtual voidFUN1 (inti) {Console.WriteLine (i); }         Public voidFun2 (A A) {A.fun1 (3); FUN1 (7); }    }         Public classb:a { Public Override voidFUN1 (inti) {Console.WriteLine (i+1); }    }         Public Static voidMain () {A A=NewA (); b b=NewB ();        A.fun2 (b);    B.fun2 (a); }}

In the above program, Class B inherits from Class A, and in the main () function, each of these two class instance variables, a, b

A.fun2 (b);

is performed as follows:
1. Object A first calls the Fun2 method of Class A, fun2 (a) requires an instance variable of type A, and here the
The actual parameter is an instance variable B of type B. So this will implicitly convert B into a type, the conversion process,
B will lose its own unique features.
2. Implementation of B.FUN1 (3), B's Fun1 method covers the Fun1 method of Class A, so the actual implementation of Class B FUN1
method, print out 4 (i+1).
3. Execute FUN1 (7), where the calling object is not specified, and the current calling object is assumed to be the default. Current is a in call, then execute
A.FUN1 (7), A is an instance variable of Class A, the fun1 of Class A is executed, and 7 (i) is printed.

B.fun2 (a);

is performed as follows:
1. Because there is no Fun2 method in Class B, the Fun2 method of its parent class A is executed, where the actual argument is an instance of type a
Variable A, so no conversion is required.
2. Perform a.fun1 (3) and print out 3 (i).
3. Execute FUN1 (7), i.e. B.FUN1 (7), print out 8 (i+1).

The final output of the program should be:
4
7
3
8

Small example Analysis C # inheritance mechanism

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.