在学习CoreJava中,看到一个构造器可以调用同一个类另个一构造器的部分,
class Employee
{
private static int nextId;
private int id;
private String name;
private double salary;
static
{
Random generator=new Random();
nextId=generator.nextInt(1000)+1;
}
{
id=nextId;
nextId++;
}
public Employee(String name,double salary)
{
this.name=name;
this.salary=salary;
}
public Employee(double s)
{
this("Employee#"+nextId,s);
}
public Employee()
{
}
}
this("Employee#"+nextId,s); 这句话没看懂,请问有人能帮忙解释一下吗?
this("Employee#"+nextId,s);,
你可以把构造器看作普通的方法,,返回类型为 当前类的类型,,那么所有构造方法返回类型都是一致的(这只是一种类比)
public Employee Employee(double s)
{
return this("Employee#"+nextId,s);
}
public Employee Employee(String name,double salary)
{
this.name=name;
this.salary=salary;
return employee;
}
注意:
这个例子只是为了方便理解,,,只是一种类比,,实际中肯定是不可以这样写的
调用你的这个方法上面的 那个构造方法
this关键字除了可以引用变量或者成员方法之外,还有一个重大的作用就是返回类的引用。
在构造方法中使this关键字表示调用类中的构造方法。如果一个类中有多个构造方法,因为其名字都相同,跟类名一致,那么这个this到底是调用哪个构造方法呢?其实,这跟采用其他方法引用构造方法一样,都是通过形式参数来调用构造方法的。
你的代码this("Employee#"+nextId,s) 就是要调用当前类两个参数的那个构造方法。
this("Employee#"+nextId,s) ,第一个参数 是字符串,值是 字符串1("Employee#") 和 字符串2 (nextId),合并的结果
补充一下,一个类中可以写多个构造方法,一般需要提供一个无参数的构造方法,多个有参数的构造方法。
其次,构造方法的参数不同,其实就是Java的方法重载,一个构造方法中调用另一个构造方法,这在JDK源码中很常见,区别可能就是某些参数使用了默认的值。