Create your own callback in Java

Creating callback in Java need utilize the interface unlike the javascript there is quite a work to creating callback pattern in Java.

using interface

public interface WordIntf{
    public void saysSomething(String salutation);
}

Create the method that call the interface

public class WordImpl{
    private String salutation;
    public WordImpl(String salutation){
        this.salutation = salutation;
    }
    public void talkToPerson(WordIntf word){
         word.saysSomething(salutation);
    }
}

from my understanding the callback its mean we call the method again and we can Implemented anything inside the interface implementation. From the above example, in method saysSomething I can implement whole conversation to talk with people, but in the first conversation I will attach the salutation to welcome the person.

Concrete Implementation

public class Main{
    public static void main(String[] args){
        //Talk To man
        WordImpl talk = new WordImpl("Mr.");
        talk.talkToPerson(new WordIntf(){
            public void saysSomething(String salutation){
                StringBuilder sb = new StringBuilder();
                String talk = "Hay are you going to gym??";
                sb.append(salutation).append(" ").append(talk);
                System.out.println(sb.toString());  
            }
        });
        //Talk to women
        WordImpl talkW = new WordImpl("Mrs.");
        talkW.talkToPerson(new WordIntf(){
            public void saysSomething(String salutation){
                StringBuilder sb = new StringBuilder();
                String talk = "Your so beautifful today madam moseile";
                sb.append(salutation).append(" ").append(talk);
                System.out.println(sb.toString());      
            }
        });    
    }
}

That’s it, happy coding

 
5
Kudos
 
5
Kudos

Now read this

Using Java Map rather than if and else (Actually this more appropriate for switch case)

Actually this idea is not such a big stuff rather just find small thing that I found so interesting. Usually we using if else or maybe switch to create logical condition until some extend the condition became so unreadable because its to... Continue →