Postscript 2020/3/15 ・ As I was told in the comments that polymorphism is a more abstract way of thinking, I corrected the relationship with overload.
This article is a memorandum. Although it is a reference book level content, the code posted in this article is about ~~ ** The mistaken ** is the center. This is for the purpose of posting the mistaken part during coding and posting it for self-reflection ~~. In addition, I will not touch on the deep part here because I will review it later while also studying the Java Silver exam questions.
Language: Java11, JDK13.0.2 Operating environment: Windows 10
In the class, there is a rule that methods with the same name can coexist. Even if the number of arguments handled in one method is increased without limit, it is difficult to declare all the arguments at once, so it is easier for the class user to prepare them separately for the necessary functions.
Cat.java
getCatStatus(double weight,double height){
(Abbreviation)
}
getCatStatus(int age,int number){
(Abbreviation)
}
getCatStatus(String name,String voice){
(Abbreviation)
}
At this time, depending on the argument specification when using getCatStatus ()
, you can select the matching method from the methods with the same name and use it.
This function is called ** overload **.
As a caveat, ** it is necessary to make the type and number of arguments of each method with the same name different **.
This doesn't include differences between return types, so you can't create a method that requires the same arguments with different qualifiers **.
When preparing a class and writing a method, the initial value of the class field can be set immediately after the object of the class is created.
Cat.java
class Cat
{
private double weight;
private int age;
public Cat()
{
weight = 1.0;
age = 0;
}
}
If you write a method with the exact same name as the class name, you can automatically store the initial value when the object is created by new
using the class.
About the function handled in the overload, which is a method with the same name but can have different functions depending on the argument. It is a mechanism of function overloading, and in particular, ** polymorphism ** in which the behavior of a function changes according to the argument type is called ** ad hoc polymorphism **.
Note: Ad hoc polymorphism is one of ** Polymorphism **
I write variables and expressions as much as possible and compile them, so if I want to quote them completely, I will describe that.
Easy Java 7th Edition Java SE11 Silver Problem Collection (commonly known as Kuromoto)
Recommended Posts