英文:
Why super() is used in Constructor?
问题
以下是您要翻译的内容:
"我在学习有关自定义 ArrayAdapter 的内容,在 GitHub 上找到了这个项目。我无法理解为什么在这里使用了 super。
public AndroidFlavorAdapter(Activity context, ArrayList<AndroidFlavor> Flavors) {
super(context, 0, Flavors);
}
当我删除 super 时,会出现以下错误。
"X 没有适用的构造函数 '()'"
有帮助吗?"
英文:
I was learning about custom ArrayAdapter.Found this project on Github. I can't figure out why super is used here.
public AndroidFlavorAdapter(Activity context, ArrayList<AndroidFlavor>Flavors) {
super(context, 0, Flavors);
}
When I remove super this error pops up.
X There is no applicable constructor to '()’
Any help?
答案1
得分: 3
每个构造函数都需要在第一件事情做的是另一个构造函数<sup>1</sup>。有三种方法可以做到这一点:
-
构造函数可以进行显式的
super
调用,可以带参数也可以不带参数。参数类型需要与在超类中声明的构造函数的签名匹配。 -
构造函数可以进行显式的
this
调用。这会调用该类声明的另一个构造函数。 -
如果没有显式的
super
或this
调用,Java编译器会在构造函数中添加隐式的super()
调用。为了使其工作,超类中需要有一个无参数的构造函数;即无参构造函数。
<sup>1 - 除了java.lang.Object
,它没有超类。请注意,字节码验证器会检查这一点。如果你使用字节码汇编器创建一个不调用超类构造函数的构造函数,它将被类加载器拒绝。</sup>
所以...
> 为什么在构造函数中使用super(...)
?
为了显式调用超类构造函数。请注意,在这种情况下,您正在向超类构造函数传递参数。
> 当我移除super时,出现了这个错误:“没有适用于'()'的构造函数”。
这是因为编译器找不到隐式调用的超类无参构造函数,如果您没有显式的super(...)
调用。
> 请问为什么super中的第二个参数是0。
超类的文档应该解释了这意味着什么。在这种情况下,第二个参数是资源ID。我不确定这是否有意义,但我曾看到有人说资源ID 0 表示null
。
英文:
Every constructor needs to another constructor as the first thing it does<sup>1</sup>. There are three ways to do this:
-
A constructor can make an explicit
super
call, either with or without parameters. The parameters types need to match the signature of a constructor declared in the superclass. -
A constructor can make an explicit
this
call. This calls another constructor declared by this class. -
If there no explicit
super
orthis
class, an implicitsuper()
call is added to the constructor by the Java compiler. For this to work, there needs to be a constructor in the superclass with no arguments; i.e. a no-args constructor.
<sup>1 - Except for java.lang.Object
which has no superclass. Note that the bytecode verifier checks this. If you use (say) a bytecode assembler to create a class with a constructor that doesn't call a superclass constructor, it will be rejected by the classloader.</sup>
So ...
> Why super(...)
is used in Constructor?
To explicitly call a superclass constructor. Notice that in this case you are passing arguments to the superclass constructor.
> When I remove super this error pops up: "There is no applicable constructor to '()’"
That is because the compiler cannot find the superclasses no-args constructor that is implicitly invoked if you don't have an explicit super(...)
call.
> Can you please tell me why the second parameter in super is 0.
The javadocs for the superclass should explain what that means. In this case, the 2nd parameter is a Resource ID. I'm not sure that it makes sense, but I've seen it said that Resource ID 0 means null
.
答案2
得分: 0
因为基类可能正在为实例进行所需的初始化。
英文:
Because the base class is probably doing the required initialization for the instance.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论