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()只调用基类的no-arg构造函数,在你的情况下是Object. 它什么都没做.它只是在代码中明确表示您正在使用no-arg构造函数构造基类.实际上,如果你离开super(),它将由编译器隐式添加. 那么,如果它是隐式添加的话,那么super()是什么呢?好吧,在某些情况下,类没有no-arg构造函数.这个类的子类必须显式调用一些超级构造函数,例如使用super(“hello”).
this.lastName = lastName;与super()无关.它只是声明构造函数参数lastName的值应该赋给成员变量lastName.这相当于 public Contact(String contactId,String lastNameArg,String phoneNumber) { // ... lastName = lastNameArg; // ... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |