Java 默认构造函数问题声明值
主要Java 默认构造函数问题声明值,java,constructor,Java,Constructor,主要 public class Employee { public Employee(){ id=-1; year=-1; salary=-1; name="NA"; department="NA"; } public Employee(int id ,String name ,String department, int year,double salary){
public class Employee {
public Employee(){
id=-1;
year=-1;
salary=-1;
name="NA";
department="NA";
}
public Employee(int id ,String name ,String department, int year,double salary){
String s="Sales";
String i="IT";
String W="Warehouse";
if(department.equals(W)) {
this.department=department;}
else
if(department.equals(s)) {
this.department=department;}
else
if(department.equals(i)) {
this.department=department;}
else
System.out.print("Department was not set");
}
我的问题是我在默认构造函数中声明了设置
int input,id ,year ;
double salary;
String name ,department;
System.out.print("Enter Employee 1 details (id, name, department, years, salary)");
id=kb.nextInt();
name=kb.next();
department=kb.next();
year=kb.nextInt();
salary=kb.nextDouble();
Employee Employee=new Employee(id, name, department, year, salary);
但当用户输入无效值时,它会打印null或0
我试着用
id=-1;
year=-1;
salary=-1;
name="NA";
department="NA";
但它同样打印
null
或0
。任何问题所在的想法都包括从全参数构造函数调用默认构造函数
Employee Employee=new Employee();
Employee=new Employee(id, name, department, year, salary);
问题是
public Employee(int id, String name, String department, int year, double salary) {
this();
// the rest
}
及
是独立的,后者只设置一个部门
字段,而您希望所有字段都被设置
new Employee(id, name, department, year, salary)
这意味着“首先填充默认值”
这个构造函数
this();
这也是一个问题。它需要很多论点,但只适用于一个论点。考虑将它们设置为
Employee(int id, String name, String department, int year, double salary)
验证条件可以简化
this.id = id;
// and others
您有多个构造函数。是否将参数分配给类变量
public Employee(int-id,String-name,String-department,int-year,double-salary){this.id=id;this.name=name;….}
通常情况下,这是另一种方式。参数较少的构造函数调用参数较多的构造函数并传递默认值,即this(-1,“NA”,“NA”,-1,-1)
this.id = id;
// and others
if (department.equals(W) || department.equals(s) || department.equals(i)) {
this.department = department;
} else {
// a message or exception
}