Optional Methods in Java Interface

后端 未结 12 1851
说谎
说谎 2020-11-30 20:53

From my understanding if you implement an interface in java, the methods specified in that interface have to be used by the sub classes implementing the said interface.

12条回答
  •  隐瞒了意图╮
    2020-11-30 21:23

    I was looking for a way to implement the call back interface, so implementing optional methods was necessary since I didn't want to implement every method for each call back.

    So, instead of using an interface, I used a class with empty implementation such as:

    public class MyCallBack{
        public void didResponseCameBack(String response){}
    }
    

    And you can set member variable CallBack like this,

    c.setCallBack(new MyCallBack() {
        public void didResponseCameBack(String response) {
            //your implementation here
        }
    });
    

    then call it like this.

    if(mMyCallBack != null) {
        mMyCallBack.didResponseCameBack(response);
    }
    

    This way, you wouldn't need to worry about implementing every methods per call back, but only override the ones you need.

提交回复
热议问题