java中的超级构造函数

Som*_*Guy 3 java constructor class super superclass

请解释

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;
}
Run Code Online (Sandbox Code Playgroud)

内部没有参数的Super()意味着要定义多个参数?这是在"this.xxx"的帮助下完成的吗?

为什么我们在"公共类联系"本身中定义.为什么我们再次定义并在此处调用其参数?

aio*_*obe 7

内部没有参数的Super()意味着要定义多个参数?

不,super()只是在你的情况下调用基类的no-arg构造函数Object.

它什么都没做.它只是在代码中明确表示您正在使用no-arg构造函数构造基类.事实上,如果你遗漏super()了,它将由编译器隐式添加.

那么super()无论如何它是隐含的添加是什么?好吧,在某些情况下,类没有no-arg构造函数.这个类的子类必须使用例如显式调用一些超级构造函数super("hello").

this.lastName = lastName; //when is this used?, when more than one args to be entered?

this.lastName = lastName;与此无关super().它只是声明构造函数参数的值lastName应该分配给成员变量lastName.这相当于

public Contact(String contactId, String firstName, String lastNameArg,
               String email, String phoneNumber) {
    // ...
    lastName = lastNameArg;
    // ...
Run Code Online (Sandbox Code Playgroud)


Boz*_*zho 6

super()调用超类的默认(no-arg)构造函数.这是因为为了构造一个对象,你必须遍历层次结构中的所有构造函数.

super() 可以省略 - 编译器会自动将其插入.

在你的情况下,超类是 Object