Appendix A training intern-object-oriented BASICS (3): Method Overloading

Source: Internet
Author: User

For the previous code, if you write Cat cat = new CAT ();, an error is reported:

1 The "cat" method does not use the "0" parameter to overload E: \ big talk Design Pattern learning \ bigdesignpatterns \ Appendix A training intern-object-oriented basics \ animal games \ animalgames \ form1.cs 20 23 animalgames

The reason is that you need to give a name to the kitten. If you need to give birth to a kitten without a name, you can use the method to reload it.

Method overloading provides the ability to create multiple methods with the same name, but these methods require different parameter types. Note that not only constructor methods can be overloaded, but also common methods.

Method overload: The method name is the same, but the parameter type or number must be different.

What are the benefits of method overloading?

The advantage of method Overloading is to add new functions without changing the original method (method overloading provides the scalability of Functions ).

Reload Cat:

1 class Cat 2 {3 private string name = ""; // declare the cat class private string variable name 4 5 // <summary> 6 // define the cat constructor, the input parameter is a string of 7 /// </Summary> 8 /// <Param name = "name"> </param> 9 Public CAT (string name) 10 {11 this. name = Name; // assign the parameter to the private variable name12} 13 14 /// <summary> 15 // The constructor reloads 16 /// </Summary> 17 Public CAT () 18 {19 this. name = ""; 20} 21 22 Public String shout () 23 {24 return "my name is" + name + ""; 25} 26}

When calling:

1 private void button#click (Object sender, eventargs E) 2 {3 CAT = new CAT (); // instantiate Cat 4 // Note: Cat cat = new CAT (); in fact, I did two things: 5 // CAT; declare a cat object. The object name is cat6 // cat = new CAT (); instantiate the cat object 7 MessageBox. show (cat. shout (); 8}

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.