一个问题

class Person {
String name;//加static
String department;
int age;//加static
int num = age;
public Person()
{
  System.out.println(name+"::"+age);
}
public Person(String n) {
  name = n;
}

public Person(String n, int a) {
  name = n;
  age = a;
}

public Person(String n, String d, int a) {
  // 完成Person(String n, int a)的逻辑
  this(name,age); //【【【此处调用出错】】】
  department = d;
}
}


对象依靠构造函数,实例成员依靠对象,所以会报错。构造函数没完成,对象建立就没完成

Within a class, the 'this' Java keyword refers to the native object, the current instance of the class. Within a constructor, you can use the thiskeyword in 3 different ways:

  • on the first line, you can call another constructor, using this(...);
  • as a qualifier when referencing fields, as in this.fName
  • as a reference passed to a method of some other object, as in blah.operation(this);

You can get into trouble with the last form. The problem is that, inside a constructor, the object is not yet fully constructed. An object is only fully constructed after its constructor completely returns, and not before. But when passed as a parameter to a method of some other object, the thisreference should always refer to a fully-formed object.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值