问题描述
我有一个生物课,另外一个是飞行与不死生物课,它扩展了生物。 如何创建同时具有飞行和亡灵属性的对象?
class Creature(){
String name;
public Creature(String name){
this.name=name;
}
class Flying extends Creature{
...
}
class Undead extends Creature{
...
}
Object creature = new Object();//Both Flying and Undead
还有另一种方法可以使用,还是应该使用其他方法?
1楼
在Java中,不能有从多个超类继承的类。 您最好使用接口,因为可以使用更多已实现的接口。 接口是类似于类的对象。 在接口中,您可以拥有变量和方法,应在实现接口的类中完成定义和给方法和变量赋值的螺母。 例如 :
Interface MyInterface
{
int myVar;
void myMethod (int var);
}
class MyClass implements MyInterface // with comma(,) you can separate multiple interfaces
{
void myMethod (int var) {//do something}
int myVar = 1;
}
使用名为Flying and Undead或Creature的接口,也许您可??以做您想做的。
您可以了解有关接口的更多信息。