问题:
Given the uncompleted code of a class:
class Person {
String name, department;
int 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) {
// doing the same as two arguments version of constructor
// including assignment name=n,age=a department = d;
}
}
Which expression can be added at the "doing the same as..." part of the constructor?()
A . Person(n,a);
B . this(Person(n,a));
C . this(n,a);
D . this(name,age);
Given the uncompleted code of a class:
class Person {
String name, department;
int 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) {
// doing the same as two arguments version of constructor
// including assignment name=n,age=a department = d;
}
}
Which expression can be added at the "doing the same as..." part of the constructor?()
● 参考解析
在同一个类的不同构造方法中调用该类的其它构造方法需要使用this(…)的形式,而且必须是在构造方法的第一行调用,这个和普通的方法重载调用的方式不同,普通的方法可以直接使用方法名加参数来调用,而且调用位置没有限制,因此答案A是不行的,B的语法就是错误的,D的错误在于在父类型的构造函数被调用前不能引用类的成员。构造方法是一个类对象实例化的起点(虽然严格来说首先执行的并不是构造方法的第一个语句,而是内存的分配),因此在构造方法中不能将成员作为参数引用。