Basic knowledge of java | Method overloading

Keep creating and accelerate growth! This is the 17th day that I participated in the "Nuggets Daily New Plan·October Update Challenge", click to view event details

Method overloading

If there are two methods with the same method name but inconsistent parameter lists, you can say that one method is an overload of the other method. The requirements for method overloading are as follows: - The method name is the same - The parameter type, number, and order of the method are different as long as one of them is different - The return type of the method can be different or the same - The modifiers of the method can be different

For example: java //定义了3个print方法,他们只是有传参的区别,所有属于方法重载 public class Father{ public void print(){ System.out.println("无参数打印方法"); } public void print(int x,String y){ System.out.println("整型在前参数方法"); } public void print(String y,int x){ System.out.println("字符串类型在前的有参数方法"); } } Note: If the parameter name passed is not the same as the previous method parameter name, an error will be reported and it does not belong to method overloading.

Polymorphism

There is a principle in object-oriented: where the parent class appears, the subclass must appear. But the converse is not necessarily true. Polymorphism is a specific manifestation of this principle. For example: when a parent class has many subclasses, and these subclasses show different behaviors when calling the same method, this phenomenon is called polymorphism.

  • Note: Polymorphism blocks the methods of the parent class. If you need to call a method of the parent class, you need to use the super keyword to call a method of the parent class. If a method of the parent class is not inherited, you can add the final keyword in front of the method.

  • Code example:

```java //Define the parent class - animal public classes Animal{ public void cry(){ System.out.println("Animals can cry"); } public void eatFood(){ System.out.println("Animals Will eat"); } public final void func(){ System.out.println("Animal: Call func() method"); } }

//Define subclasses of cats and dogs public class cat extends Animal{ public void cry(){ System.out.println("Cats can meow"); } public void eatFood(){ System.out.println("Cats Can eat fish"); } public class dog extends Animal{ public void cry(){ System.out.println("The dog can bark"); } public void eatFood(){ System.out.println("The dog can eat shi"); } } ``` Both subclasses overload the cry() and eatFood() methods of the animal class, but different sounds appear after calling the cry method...

Guess you like

Origin blog.csdn.net/y943711797/article/details/132978544