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”的帮助下完成的吗?
为什么我们在“公共类联系人”本身中定义。为什么我们在这里再次定义并调用它的参数?
Please explain
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() with no arguments inside mean there are more than one arguments to be defined? And is this done with the help of "this.xxx" ?
Why dint we define in the "public class Contact" itself. Why we defined again and called its arguments here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,
super()
只是调用基类的无参数构造函数,在您的案例对象
。它实际上什么也没做。它只是在代码中明确表明您正在使用无参数构造函数构造基类。事实上,如果您将
super()
排除在外,编译器会隐式地将其添加回来。那么如果
super()
是隐式添加的,那么它的作用是什么?嗯,在某些情况下,类没有无参数构造函数。此类的子类必须显式调用某些超级构造函数,例如使用super("hello")
。this.lastName = lastName;
与super()<无关/代码>。它只是指出构造函数参数
lastName
的值应分配给成员变量lastName
。这相当于No,
super()
just calls the no-arg constructor of the base class, in your caseObject
.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.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 instancesuper("hello")
.this.lastName = lastName;
has nothing to do withsuper()
. It merely states that the value of the constructor argumentlastName
should be assigned to the member variablelastName
. This is equivalent tosuper()
调用超类的默认(无参数)构造函数。这是因为为了构造一个对象,您必须遍历层次结构中的所有构造函数。super()
可以省略 - 编译器会自动将其插入那里。在您的情况下,超类是
Object
super()
calls the default (no-arg) constructor of the superclass. This is because in order to construct an object, you have to go through all the constructors up the hierarchy.super()
can be omitted - the compiler automatically inserts it there.In your case, the superclass is
Object