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}