Java编程实现实现一个金丝猴类,要求其继承自动物类,并实现包括金丝猴是受保护而且是有价值的动物的多重继承的功能。
时间: 2024-01-22 10:19:43 浏览: 62
Java编程思想之接口Java中实现多重继承.doc
下面是Java编程实现一个金丝猴类的示例代码:
```java
public class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
public interface ProtectedAnimal {
public void protect();
}
public interface ValuableAnimal {
public void value();
}
public class GoldenMonkey extends Animal implements ProtectedAnimal, ValuableAnimal {
public GoldenMonkey(String name, int age) {
super(name, age);
}
public void protect() {
System.out.println(name + " is a protected animal.");
}
public void value() {
System.out.println(name + " is a valuable animal.");
}
}
```
在上述代码中,金丝猴类GoldenMonkey继承自动物类Animal,并实现了ProtectedAnimal和ValuableAnimal两个接口。ProtectedAnimal接口定义了protect方法,ValuableAnimal接口定义了value方法,GoldenMonkey类实现了这两个方法,以实现多重继承的功能。
阅读全文