Java takes methods as parameters — instances of polymorphism

When studying the intelligent algorithm in the previous paragraph, I found that if it is implemented in Java, the specific implementation process is almost the same, but the fitness function is based on

Great changes have taken place in the different research objects, which has a great obstacle to the maintenance of the code. Therefore, a question arises: can the fitness function be used

Pass in the method as a parameter. According to the habit of C / C + +, the function can be passed in as a pointer due to the existence of the pointer. Due to the complexity of Pointer use

And difficult to maintain, with average effect. If you change an object-oriented idea, you can want to design an interface I, which only provides one method, then the phase

When the interface can be passed as a parameter into the method, it is necessary to design a class to implement the interface I, so that the function can be passed into the method.

Next, take the 0.618 gold search method as an example. Due to different objective functions, it meets the requirements described above. Note that this search is only feasible when the function of single peak is used,

The algorithm is shown in the following figure:

1. First create an interface, which has only one adaptation value method:

2. Create a class to simply implement the above 0.618 search method:

3. Create a class to implement the fitness interface, that is, write your own objective function. Here, take the univariate quadratic function as an example:

4. Simply call:

In summary, there are many parameters to be added. You can pass the value into the interface implementation class, so the getfitness method can access this parameter.

The above example of Java taking methods as parameters -- polymorphism is all the content shared by Xiaobian. I hope it can give you a reference and support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>