Java中的超级构造函数 [英] Super constructor in java
问题描述
请解释
public class Contact {
private String contactId;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
public Contact(String contactId,String firstName, String lastName, String email, String phoneNumber) {
super(); //what does standalone super() define? With no args here?
this.firstName = firstName;
this.lastName = lastName; //when is this used?, when more than one args to be entered?
this.email = email;
this.phoneNumber = phoneNumber;
}
Super()里面没有参数,意味着有多个参数定义的?并借助 this.xxx完成此操作吗?
Super() with no arguments inside mean there are more than one arguments to be defined? And is this done with the help of "this.xxx" ?
为什么我们在公共类联系人本身中定义了dint。为什么我们要再次定义并在此处调用其参数?
Why dint we define in the "public class Contact" itself. Why we defined again and called its arguments here?
推荐答案
Super()不带
否, super( )
只是调用基类的no-arg构造函数,在您的情况下是 Object
。
No, super()
just calls the no-arg constructor of the base class, in your case Object
.
它什么也没做。它只是在代码中明确指出,您正在使用no-arg构造函数构造基类。实际上,如果省略 super()
,编译器将隐式地将其添加回去。
It does nothing really. It just makes it explicit in the code, that you're constructing the base class using the no-arg constructor. In fact, if you left super()
out, it would be added back implicitly by the compiler.
因此 super()
的含义是什么?好吧,在某些情况下,类没有no-arg构造函数。此类的子类必须使用诸如 super( hello)
显式调用某些超级构造函数。
So what is the super()
for if it's added implicitly anyway? Well, in some cases, a class does not have a no-arg constructor. Subclasses of this class must explicitly call some super-constructor, using for instance super("hello")
.
this.lastName = lastName; //何时使用此参数?何时输入多个参数?
this.lastName = lastName; //when is this used?, when more than one args to be entered?
this.lastName = lastName;
与 super()
无关。它仅说明构造函数自变量 lastName
的值应分配给成员变量 lastName
。等效于
this.lastName = lastName;
has nothing to do with super()
. It merely states that the value of the constructor argument lastName
should be assigned to the member variable lastName
. This is equivalent to
public Contact(String contactId, String firstName, String lastNameArg,
String email, String phoneNumber) {
// ...
lastName = lastNameArg;
// ...
这篇关于Java中的超级构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!