简体   繁体   English

何时在匿名类中创建方法

[英]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. 在下面的代码中,我创建了按钮侦听器,当尝试创建on() eclipse方法时on()建议将其创建为OnClickListenerOnClickListener一部分。

What is the difference beteen creating the method on() in both cases, and why it should be protected ? 在两种情况下创建方法on()的区别是什么?为什么要对其进行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. 在您的情况下,由于您可能不需要从OnClickListener任何其他位置调用on()方法,因此这是放置它的正确位置。

In that case the on() method should be private because you will never extend the anonymous OnClickListener class. 在那种情况下, on()方法应该是私有的,因为您将永远不会扩展匿名的OnClickListener类。 If your listener was not anonymous, you may want to declare the method protected so that you can override the implementation in subclasses 如果您的侦听器不是匿名的,则可能需要声明该方法为受保护的方法,以便可以覆盖子类中的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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