Function transfer in Java

Source: Internet
Author: User

In C and C ++, function passing can be implemented through function pointers. In C #, function transfer can be implemented through delegation, Action, and Func. In Java, there are no function pointers and no delegation. How should the functions be passed?

You can use either of the following methods.

1. Use handler to instantiate Class B in Class A and pass A handler to Class B. B sends A message through handler. After receiving the message in A, execute the corresponding function. Strictly speaking, this is not a function transfer, but a disguised function call.

2. Implemented through interfaces. The following is the implementation code.

ICallback. java

Package com. sparkle. sgmjl; public interface ICallback {abstract void callback (String data );}

Pass ICallback to Class B in Class A. The Code is as follows.

ClassA. java

ClassA classA = new ClassA (new ICallback () {@ Overridepublic void callback (String data) {Test (data) ;}}); private void Test (String data) {Log. e ("TEST", data ))}


ClassB. java

Public ClassB (ICallback icallback) {icallback ("Call OK ");}


The preceding notes are for future use.

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.