简体   繁体   中英

When to create a method inside anonymous class

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

}

Encapsulation is the concept that should give you a lead on where to place the method. Encapsulation helps you hide your implementation details to the most limited scope so that, eg, you can prevent ripple effect when you need to change the implementation.

In your case, since you probably don't need to call the on() method from any other place then your OnClickListener , this is the right place to put it.

In that case the on() method should be private because you will never extend the anonymous OnClickListener class. If your listener was not anonymous, you may want to declare the method protected so that you can override the implementation in subclasses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM