Java C # difference: Use a parent variable to call the subclass Method

Source: Internet
Author: User

Let's take a look at the Java situation.

Public class program1 extends program0 {
Public string name = "son ";
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Program0 P = new program1 ();
P. Method (); // output: subclass
System. Out. println (P. Name); // output: Father
}
@ Override
Public void method (){
System. Out. println ("subclass ");
}
}

Class program0 {
Public string name = "father ";
Public void method (){
System. Out. println ("parent class ");
}
}

All member methods of the Java class can be inherited by default. If the access permission is not private. When an instance of a subclass is assigned to a variable of the parent class, the override method is called using the variable. What we actually call is the subclass method. But the variable is the parent class. This is what we usually call it. member variables, static members, and static methods are bound to classes, and member methods are bound to instances.

C # situation

All member methods in C # cannot be inherited by default, which is the opposite of Java. Then, the method binding starts recursion from the base class (the base class here refers to the class at the top of the hierarchy, but the class declared by the variable, if the method of the base class is visual and the override of the direct subclass is performed, the method of the direct subclass is called, otherwise, when the base class method is non-virtual or virtual, but the direct subclass does not override, the base class method is called.

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.