[英]How to define a explicit constructor when the parent class doesn't have a default constructor?
[英]How to call constructor of parent class when the default constructor is deprecated
我有一個名為BaseKeyListener的類,該類擴展了android.text.method.DigitsKeyListener。 我沒有在BaseKeyListener類中定義構造函數,因此調用了父級默認構造函數。
從API級別26開始, 不建議使用 DigitsKeyListener的默認構造函數。 為了仍然支持較低的Android版本,我必須向BaseKeyListener添加一個構造函數,該構造函數有條件地調用父級的構造函數。 但是,這將導致另一個錯誤。
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()”必須是構造函數主體中的第一條語句
我嘗試了一個簡寫的if語句,但這也沒有解決問題。 還有另一個 api 1級構造函數,但不幸的是它也已棄用。 我該如何解決這些錯誤?
我會這樣想:
/**
* 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);
}
不推薦使用的構造函數仍存在於API 26+中,並且傳遞空語言環境與無論如何都調用默認構造函數相同 。 您可以覆蓋默認的構造函數,也可以覆蓋兩者,然后添加靜態方法來調用正確的構造函數,具體取決於運行的Android版本。
public static abstract class BaseKeyListener extends DigitsKeyListener {
public BaseKeyListener() {
super();
}
}
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();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.