public Animal(String name, int age) { this.name = name; this.age = age; }这不是提供了吗
时间: 2024-03-05 13:51:12 浏览: 60
是的,你说得对,我之前的回答有些模糊。在这个例子中,父类 `Animal` 已经提供了带有参数的构造函数 `Animal(String name, int age)` 来初始化属性,因此在子类 `Cat` 和 `Dog` 中可以使用 `super(name, age)` 来调用父类的构造函数,以初始化继承自父类的属性 `name` 和 `age`。
在这种情况下,子类的构造函数中可以不写 `super(name, age)`,编译器会自动调用父类的带有参数的构造函数,但是建议在子类的构造函数中显式地调用父类的构造函数,以提高代码的可读性和可维护性。
因此,以下是更新后的代码示例:
```java
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println("The animal is eating.");
}
public void sleep() {
System.out.println("The animal is sleeping.");
}
}
public class Cat extends Animal {
private boolean isIndoor;
public Cat(String name, int age, boolean isIndoor) {
super(name, age);
this.isIndoor = isIndoor;
}
public void meow() {
System.out.println("The cat is meowing.");
}
@Override
public void eat() {
System.out.println("The cat is eating fish.");
}
}
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age);
this.breed = breed;
}
public void bark() {
System.out.println("The dog is barking.");
}
@Override
public void eat() {
System.out.println("The dog is eating meat.");
}
}
```
阅读全文