不建议使用默认构造函数时如何调用父类的构造函数 [英] How to call constructor of parent class when the default constructor is deprecated

查看:95
本文介绍了不建议使用默认构造函数时如何调用父类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为BaseKeyListener的类,该类扩展了android.text.method.DigitsKeyListener.我没有在BaseKeyListener类中定义构造函数,因此调用了父级默认构造函数.

I have a class called BaseKeyListener that extends android.text.method.DigitsKeyListener. I didn't define a constructor in the BaseKeyListener class so the parents default constructor was called.

从api级别26开始,DigitsKeyListener的默认构造函数为

As of api level 26 the default constructor of DigitsKeyListener is deprecated. In order to still support lower Android versions I would have to add a constructor to BaseKeyListener that conditionally calls the constructor of the parent. However this results in another error.

public static abstract class BaseKeyListener extends DigitsKeyListener
{
    public BaseKeyListener()
    {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            // api level 26 constructor
            super(null);
        }
        else 
        {
            // api level 1 constructor (deprecated)
            super(); 
        } 
    }
}

我现在遇到的错误:

对"super()"的调用必须是构造函数主体中的第一条语句

Call to 'super()' must be first statement in constructor body

我尝试了一个简写的if语句,但这也没有解决问题.有另一个 api1级构造函数,但不幸的是它也已弃用.我该如何解决这些错误?

I tried a shorthand if statement but that also didn't do the trick. There was another api level 1 constructor but unfortunately it's also deprecated. What can I do to fix these errors?

推荐答案

API 26+和

The deprecated constructor still exists in API 26+ and passing in a null locale is the same as calling the default constructor anyway. You can either just override the default constructor or override both and add a static method to call the right constructor depending on which version of Android it's running on.

public static abstract class BaseKeyListener extends DigitsKeyListener {
  public BaseKeyListener() {
    super(); 
  }
}

选项2-两个私有构造函数

public static abstract class BaseKeyListener extends DigitsKeyListener {
  private BaseKeyListener() {
    super(); 
  }

  private BaseKeyListener(Locale locale) {
    super(locale);
  }

  public static BaseKeyListener newInstance(Locale locale) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      return new BaseKeyListener(locale);
    } else {
      return new BaseKeyListener();
    }
  }
}

这篇关于不建议使用默认构造函数时如何调用父类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆