. 创建一个类 Animal,用构造法重载实现相关成员变量的初始化, 并在主类 TestTwo 里分别调用重载的构造方法创建 Animal 对象,在 屏幕上输出 Animal 初始化后的成员变量值
时间: 2023-05-26 12:04:52 浏览: 78
```
public class Animal {
private String name;
private int age;
public Animal() {
System.out.println("无参构造方法被调用");
}
public Animal(String name) {
this.name = name;
System.out.println("重载构造方法1被调用");
}
public Animal(String name, int age) {
this.name = name;
this.age = age;
System.out.println("重载构造方法2被调用");
}
public void show() {
System.out.println("name: " + name + ", age: " + age);
}
}
public class TestTwo {
public static void main(String[] args) {
Animal animal1 = new Animal();
animal1.show();
Animal animal2 = new Animal("小狗");
animal2.show();
Animal animal3 = new Animal("小猫", 3);
animal3.show();
}
}
```
输出结果:
```
无参构造方法被调用
name: null, age: 0
重载构造方法1被调用
name: 小狗, age: 0
重载构造方法2被调用
name: 小猫, age: 3
```
阅读全文