实现一个金丝猴类,要求继承自动物类,并实现包括金丝猴,是受保护,而且是有价值的动物的多重寄存的功能,用Java 编写
时间: 2023-12-20 20:04:49 浏览: 22
好的,以下是Java代码实现:
```java
// 动物类
class Animal {
// 动物名称
String name;
// 是否受保护
boolean isProtected;
// 构造函数
public Animal(String name, boolean isProtected) {
this.name = name;
this.isProtected = isProtected;
}
// 动物的介绍
public void introduce() {
System.out.println("我是一只" + name);
}
}
// 金丝猴类
class GoldenMonkey extends Animal {
// 是否有价值
boolean isValuable;
// 构造函数
public GoldenMonkey(String name, boolean isProtected, boolean isValuable) {
super(name, isProtected);
this.isValuable = isValuable;
}
// 多重寄存的功能
public void multipleInheritance() {
System.out.println("我是一只金丝猴,我实现了多重继承,我既是动物,又是有价值的受保护动物");
}
// 金丝猴的介绍
public void introduce() {
super.introduce();
System.out.println("我是一只" + (isProtected ? "受保护的" : "未受保护的") + (isValuable ? "有价值的" : "无价值的") + "金丝猴");
}
}
// 测试类
public class Test {
public static void main(String[] args) {
GoldenMonkey monkey = new GoldenMonkey("金丝猴", true, true);
monkey.introduce();
monkey.multipleInheritance();
}
}
```
运行结果为:
```
我是一只金丝猴
我是一只受保护的有价值的金丝猴
我是一只金丝猴,我实现了多重继承,我既是动物,又是有价值的受保护动物
```