大家好,我需要一些帮助来解释这个代码,以了解更好的构造函数和方法。为什么java首先调用First构造函数,NOT Default?:
public class Human {
private String name;
private int age;
public Human() {
this("Alex", 25);
System.out.println("Default constructor called");
}
public Human(String name, int age) {
this.name = name;
this.age = age;
System.out.println("First constructor called");
}
public Human(String name) {
this.name = name;
System.out.println("Second constructor called");
}
public String info(){
return name+" "+age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
} }
和
package com.company;
public class Main {
public static void main(String[] args) {
System.out.println("Create object 1");
Human person = new Human();
System.out.println(person.info());
System.out.println("Create object 2");
Human person2 = new Human("Mike",55);
System.out.println(person2.info());
}
}
所以输出是:
Create object 1
First constructor called
Default constructor called
Alex 25
Create object 2
First constructor called
Mike 55
答案 0 :(得分:3)
这句话:
Human person = new Human();
将调用默认构造函数,其定义如下:
public Human() {
this("Alex", 25);
System.out.println("Default constructor called");
}
现在第一个语句this("Alex",25)
将调用此处定义的另一个构造函数:
public Human(String name, int age) {
this.name = name;
this.age = age;
System.out.println("First constructor called");
}
这个其他构造函数设置了一些实例字段然后打印"第一个构造函数名为",当它完成时,我们返回到this("Alex",25)
的默认构造函数,然后打印到下一个打印&#的语句34;默认构造函数名为"。
简而言之:你的打印成功调用另一个构造函数,这使你认为第一个调用了另一个构造函数。
答案 1 :(得分:3)
这完全符合预期,让我们汇总函数调用:
System.out.println("Create object 1");
Human person = new Human();
--this("Alex", 25);
----this.name = name;
----this.age = age;
----System.out.println("First constructor called");
--System.out.println("Default constructor called");
System.out.println(person.info());
System.out.println("Create object 2");
Human person2 = new Human("Mike",55);
--this.name = name;
--this.age = age;
--System.out.println("First constructor called");
System.out.println(person2.info());