Reputation: 237
I have a class Creature with another class Flying and Undead that extends Creature. How could I create a object that have both the Flying and Undead attributes?
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
Is there another way to do it or should I use a different approach?
Upvotes: 1
Views: 123
Reputation: 237
In Java you can not have a class that is inherited from more than one super class. you better use Interfaces, because you can use more many implemented Interfaces. Interfaces are objects similar to classes. in Interfaces you can have variables and and methods, nut defining and giving values to methods and variables should be done in the class that implemented the Interfaces. For example :
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;
}
with Interfaces named Flying and Undead or Creature maybe you can do what you want.
here you can learn more about Interfaces.
Upvotes: 2