我想创建一个Creature类,它将成为所有生物(如人类)的父类。
所以我写了一个具有适当遗产的生物课和人类课。
由于我希望所有的生物做一些事情并且我不想为Creature类中的每个行为创建一个默认函数,我创建了一个由所有生物实现的CreatureInterface。
这是代码:
creature.vala:
// Different kind of genders
public enum GENDER
{
MALE,
FEMALE
}
// Different kind of moods
public enum MOOD
{
HAPPY,
SAD,
NEUTRAL
}
// Different kind of body size for basic physical representation
public enum BODY_SIZE
{
STANDARD,
TALL,
SMALL
}
// Different kind of body weight for basic physical representation
public enum BODY_WEIGHT
{
STANDARD,
FAT,
THICK
}
public class Creature
{
// Physic
protected BODY_SIZE _body_size = BODY_SIZE.STANDARD;
protected BODY_WEIGHT _body_weight = BODY_WEIGHT.STANDARD;
// Mental
protected MOOD _mood = MOOD.NEUTRAL;
// Social
protected GENDER _gender = GENDER.MALE;
protected string _name = "";
protected string _family_name = "";
protected Creature _mother = null;
protected Creature _father = null;
protected List<Creature> _children = null;
// Reproduction
protected int _number_of_babies_by_pregnancy = 0;
protected int _uncommon_number_of_babies_by_pregnancy = 0;
protected int _very_uncommon_number_of_babies_by_pregnancy = 0;
protected int _pregnancy_duration = 0; // In days
public Creature ()
{
if ( Random.int_range(0, 2) == 1.0 )
{
this._gender = GENDER.MALE;
}
else
{
this._gender = GENDER.FEMALE;
}
}
~Creature ()
{
stdout.printf( "I'm dying" );
}
}
public interface CreatureInterface
{
// Generate a name with specific rules for species
protected abstract void generateName();
// Get a goal for the next action
public abstract void getAGoal();
}
human.vala:
public class Human : Creature, CreatureInterface
{
public Human ()
{
// Get a name for our new human being
this.generateName();
// Social
string name = this._name;
string family_name = this._family_name;
if ( this._gender == GENDER.MALE )
{
stdout.printf( @"Say \"hello\" to $family_name $name, a human male baby.\n" );
}
else
{
stdout.printf( @"Say \"hello\" to $family_name $name, a human female baby.\n" );
}
// Reproduction
this._number_of_babies_by_pregnancy = 1;
this._uncommon_number_of_babies_by_pregnancy = 2;
this._very_uncommon_number_of_babies_by_pregnancy = 3;
this._pregnancy_duration = 275; // 9 months
}
/**
* Destructor
*/
~Human ()
{
}
public void generateName()
{
if ( this._gender == GENDER.MALE )
{
this._name = "Jhon";
}
else
{
this._name = "Jane";
}
this._family_name = "Doe";
}
public void getAGoal()
{
stdout.printf("I need a goal...");
}
}
main.vala:
public class Main
{
public static int main (string[] args)
{
stdout.printf( "Genesis\n" );
Creature john_doe = new Human();
john_doe.getAGoal();
return 0;
}
}
现在当我编译时,我有以下错误,我不明白:
./src/main.vala:9.4-9.20: error: The name `getAGoal' does not exist in the con
text of `Creature?'
john_doe.getAGoal();
^^^^^^^^^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)
make: *** [build] Erreur 1
getAGoal
已在人工中实施,且为public
。
那么,为什么它无法到达?
答案 0 :(得分:1)
具有该方法的是CreatureInterface,而不是Creature。