Reputation: 1
This is from a much larger project, so I'm going to simplify the structures and not include all of the code involved here, but I want to know if this conceptually will work and if there are potential snags that I may be having.
I have several levels of subclass from the main class, one level contains the method age() (overridden from the top superclass) which calls useEnergy(). The direct subclass of this class overrides age(). The direct subclass of that class needs to override useEnergy(), but the code in the overridden method never executes (verified with System.out.printlns). Interestingly, in the superclass of the class having problems, the one overriding age(), if I override useEnergy() in there, the code from that class executes. age() is called from outside of all of the classes, on the object. A hierarchy map looks something like this:
Is there a problem with this hierarchy? Is there something I can to to get the code in useEnergy() in Yeast to execute when age() is called on a Yeast object in an array of Entity s from within World?
The actual code for Organism's useEnergy() (working) is:
public void useEnergy(){ //Called every hungerTime, by default
energy-- ;
heat++ ;
nutrientReduction() ;
}
and the overridden method in Yeast (not working) is:
public void useEnergy(){
Random rand = new Random() ;
super.useEnergy() ;
System.out.println("Yeast energy!") ;
if(rand.nextInt(100) < 5){
toxicity += 6 ;
emitToxins(1) ;
}
}
The console never displays "Yeast energy!" even though it properly executes the code in Organism's useEnergy(). I have also verified that other subclasses of AdvancedOrganism exhibit similar behavior. Ideas?
Upvotes: 0
Views: 4071
Reputation: 1
Thank you for the comments! It did turn out to be that. I had myself convinced otherwise because in the Yeast constructor, there were class-specific settings (like a name String) that were properly passed on, but I had been generating new objects through a newCopy() method in each superclass that returned a copy of the current object using a copy constructor (passing an object to duplicate as a parameter and copying all the properties). I had not redefined newCopy to return a Yeast object, instead the program was using AdvancedOrganism's newCopy method which copied all of the properties of Yeast, but which did not actually return a Yeast object, it returned an AdvancedOrganism object with all of Yeast's properties.
I hadn't run into the problem before because other subclasses of AdvancedOrganism had been only a default constructor with some preset variables - no actual methods so copying them as if they were AdvancedOrganisms wasn't making a problem.
I added:
Yeast(Yeast parentOrganism){
super(parentOrganism.xLocation, parentOrganism.yLocation, parentOrganism.zLocation, parentOrganism) ;
}
and
public Yeast newCopy(){ //Important for SpawnRandomizer
return new Yeast(this) ;
}
And now it's operating correctly!
Upvotes: 0