When to create a method inside anonymous class

时间:2015-08-23 10:53:38

标签: java android class onclicklistener protected

In the code below, I created the button listener and when I tried to create the method on() eclipse suggested to create it as part of the OnClickListener or as part of the mainClass.

What is the difference beteen creating the method on() in both cases, and why it should be protected?

code:

private OnClickListener btnListenerOn = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        on();
    }
};
@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Log.w(TAG, "@onStart.");
}

protected void on() {
    // TODO Auto-generated method stub

}

1 个答案:

答案 0 :(得分:3)

Encapsulation这个概念可以帮助您找到放置方法的位置。封装可帮助您将实施细节隐藏到最有限的范围内,以便例如在需要更改实施时阻止ripple effect

在您的情况下,由于您可能不需要从任何其他地方调用on()方法,而不是OnClickListener,因此这是放置它的正确位置。

在这种情况下,on()方法应该是私有的,因为您永远不会扩展匿名OnClickListener类。如果您的监听器不是匿名的,您可能希望声明受保护的方法,以便您可以覆盖子类中的实现