java 超构造函数,Java中的超级构造函数

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?

解决方案

Super() with no arguments inside mean there are more than one arguments to be defined?

No, super() just calls the no-arg constructor of the base class, in your case Object.

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 instance super("hello").

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

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;

// ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值