我有一个生物类,还有另一个扩展生物类的飞行类和不死类。如何创建一个同时具有飞行和不死属性的对象?
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
是否有其他方法可以做到这一点,或者我应该使用不同的方法?
最佳答案
在 Java 中,你不能拥有一个从多个父类(super class)继承的类。您最好使用接口(interface),因为您可以使用更多已实现的接口(interface)。 接口(interface)是类似于类的对象。在接口(interface)中,您可以拥有变量和方法,但应该在实现接口(interface)的类中定义方法和变量并为其赋值。 例如:
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和Undead或Creature的界面也许你可以做你想做的事。
here您可以了解有关接口(interface)的更多信息。
关于java - 如何创建具有不同java类属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31868944/