How to call constructor of parent class when the default constructor is deprecated

有些话、适合烂在心里 提交于 2021-01-07 01:41:11

问题


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.

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(); 
        } 
    }
}

The error I'm getting now:

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

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?


回答1:


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.

Option 1 - Default constructor

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

Option 2 - Two private constructors

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();
    }
  }
}



回答2:


I would think something like this:

/**
 * only use this if you want to use api level 1
 */
public BaseKeyListener() {
  super(); // implicitly added already
}

/**
 * only use this if you want to use api level 26
 * and add if condition before calling this constructor
 */
public BaseKeyListener(Obect param) {
  super(param);
}


来源:https://stackoverflow.com/questions/51299553/how-to-call-constructor-of-parent-class-when-the-default-constructor-is-deprecat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!