父类Pet和子类Dog,Cat添加有参和无参构造函数,测试子类的使用。
时间: 2024-03-10 20:47:58 浏览: 22
好的,可以按照以下步骤添加构造函数并测试子类的使用:
1. 创建一个父类 Pet:
```
public class Pet {
private String name;
private int age;
private String species;
// 无参构造函数
public Pet() {
}
// 有参构造函数
public Pet(String name, int age, String species) {
this.name = name;
this.age = age;
this.species = species;
}
// getter和setter方法
// ...
}
```
2. 创建两个子类 Dog 和 Cat:
```
public class Dog extends Pet {
private String breed;
// 无参构造函数
public Dog() {
}
// 有参构造函数
public Dog(String name, int age, String species, String breed) {
super(name, age, species);
this.breed = breed;
}
// getter和setter方法
// ...
}
public class Cat extends Pet {
private boolean isIndoor;
// 无参构造函数
public Cat() {
}
// 有参构造函数
public Cat(String name, int age, String species, boolean isIndoor) {
super(name, age, species);
this.isIndoor = isIndoor;
}
// getter和setter方法
// ...
}
```
3. 在主程序中测试子类的使用:
```
public class MainProgram {
public static void main(String[] args) {
// 创建一个 Dog 对象并输出信息
Dog dog = new Dog("小狗", 2, "狗", "金毛");
System.out.println(dog.getName() + " " + dog.getAge() + "岁 " + dog.getSpecies() + " " + dog.getBreed());
// 创建一个 Cat 对象并输出信息
Cat cat = new Cat("小猫", 1, "猫", true);
System.out.println(cat.getName() + " " + cat.getAge() + "岁 " + cat.getSpecies() + " " + (cat.isIndoor() ? "室内" : "室外"));
}
}
```
这样就可以测试子类的使用了。