我不敢相信我在这里没有找到任何关于这个问题的内容,所以:
为什么在派生类时需要显式定义父类(super class)的所有构造函数。当派生类没有提供具有该签名的构造函数时,为什么 Java 不会自动调用 super 构造函数。
这将是一些不错的“语法糖”。
例如:在 Android 中,每个 View 子类都提供 3 个构造函数,可以从 XML 或代码调用。为了能够在代码和 XML 中创建自定义 View ,我需要定义所有三个构造函数,即使它们不执行任何操作。这是一个小例子我 had to write yesterday
public class OverfocusableGridView extends GridView {
public OverfocusableGridView(Context context) {
super(context);
}
public OverfocusableGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public OverfocusableGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean keyHandled = false;
if (this.getSelectedView() != null) {
int focusedViewPosition = this.getSelectedItemPosition();
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (focusedViewPosition > 0) {
int prevItemPosition = focusedViewPosition - 1;
this.setSelection(prevItemPosition);
keyHandled = true;
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (focusedViewPosition < this.getChildCount() - 1) {
int nextItemPosition = focusedViewPosition + 1;
this.setSelection(nextItemPosition);
keyHandled = true;
}
break;
default:
keyHandled = super.onKeyDown(keyCode, event);
}
} else {
keyHandled = super.onKeyDown(keyCode, event);
}
return keyHandled;
}
}
如果我不需要定义这些构造函数,那就更好了。这种方法有什么缺点吗?或者是否有一些 Java 设计决策可以解释这一点?
长话短说:这是不可能的吗?
最佳答案
假设构造函数被继承...那么因为每个类最终都派生自Object,每个类最终都会有一个无参数构造函数。这是个坏主意。您到底期望什么:
FileInputStream stream = new FileInputStream();
做什么?
现在可能应该有一种方法可以轻松创建相当常见的“传递”构造函数,但我认为它不应该是默认值。构造子类所需的参数通常与父类(super class)所需的参数不同。
<小时/>答案取自: https://stackoverflow.com/a/1644410/1724097
如果没有“继承”这个词,很难找到其他问题,所以我理解为什么你没有找到答案(:
关于java - 需要在重写的类中定义显式构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19807214/