1

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?

3
  • Is this a homework problem? Commented Jul 26, 2015 at 15:30
  • No, I want to implements a "Creature" system for a game. We can create a "Human", "Zombie", "Flying" creatures, like MTG cards type line (You can have multiples types for one card). So a creature can be "Flying" and "Human" (like an angel). The questions is about how to create such creature than can share attributes from the human and the flying. Commented Jul 26, 2015 at 22:08
  • Sounds like a mixin. Commented Jul 27, 2015 at 21:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.