本文介绍了重载构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从一本书中读取重载的构造函数后,我累了以下代码:

  public class Employee {

字符串名称;
int idNumber;

public Employee(){
this(JJ,0);
System.out.println(name ++ idNumber);
}

public Employee(String name,int num){

this.name = name;
idNumber = num;
System.out.println(name +2nd+ idNumber);
}
}


public class Object1 {

public static void main(String [] args){

Employee emp = new Employee();
}

}

OUTPUT:

  JJ第2 0 

JJ 0

我真的很困惑。为什么JJ第二0打印出来然后JJ 0??我创建了一个雇员对象emp,没有传递参数中的任何参数,不是先调用第一个构造函数。

解决方案

p> new Employee(); 正在调用

  {
this(JJ,0);
System.out.println(name ++ idNumber);
}

在此构造函数中



this(JJ,0);



正在调用



public Employee(String name,int num)



构造函数, / p>

System.out.println(name +2nd+ idNumber);



负责列印。

此(JJ,0); 将完成系统.out.println(name ++ idNumber); 将被调用,你应该看到另一行


After reading overloaded constructors from a book, i tired the following code:

public class Employee {

    String name;
    int idNumber;

    public Employee(){
        this("JJ", 0);
        System.out.println(name +" "+ idNumber);
    }

    public Employee(String name, int num){

        this.name = name;
        idNumber = num;
        System.out.println(name +" 2nd "+ idNumber);
    }
}


public class Object1 {

    public static void main(String[] args) {

        Employee emp = new Employee();
    }

}

OUTPUT:

JJ 2nd 0

JJ 0

I am really confused. Why "JJ 2nd 0" printed out first then "JJ 0"?? I created an employee object emp and did not pass any args in the parameter, isn't suppose to call the first constructor first?

解决方案

new Employee(); is invoking

public Employee(){
    this("JJ", 0);
    System.out.println(name +" "+ idNumber);
}

In this constructor

this("JJ", 0);

is invoking

public Employee(String name, int num)

constructor, which ends with call

System.out.println(name +" 2nd "+ idNumber);.

which is responsible for printing

When this("JJ", 0); will finish System.out.println(name +" "+ idNumber); will be invoked and you should see another line

这篇关于重载构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 09:20