abstract class structure - cannot find symbol error
This is for an assignment. (Cross post - http://www.codeguru.com/forum/showthread.php?t=384691)
I have to keep track of different produce types. To do this, I have created a class structure as follows:
Code:
abstract class Produce
abstract class Crop extends Produce
abstract class Livestock extends Produce
class Wheat extends Crop
class Apple extends Crop
class Cow extends Livestock
class Sheep extends Livestock
The code was written in this fashion to allow for other produce types to be added into the system as required.
Produce creates abstract methods that are common to all produce types (eg getSaleValue(), getMonthlyCosts()) as well as concrete methods (eg getProduceName())
Crop and Livestock introduce abstract methods and concrete methods that are particular to crops and livestock (eg Crop has getMaturity()).
Wheat - Sheep define all of the classes necessary.
.
Anyhoo...
Due to the necessay generic nature of the produce types (ie land can have Produce), all new produce is created as Produce p = new Wheat() (or new Cow() etc...).
Now I'm running into the problem that I can't access the methods introduced in Crop and Livestock, as the produce is all of type Produce, and the methods don't exist in there. These are compilation errors.
I've probably done something very stupid, and just can't recall something from one of my first lectures (or I'm not looking up the correct key words), but how can I access (for instance) getMaturity() from object p, when I create p as Produce p = new Wheat()
Sample code and error:
Code:
Produce a = new Wheat();
Produce b = new Cow();
// add some more produce related constructors here
//p has been defined previously as a type of produce as in the example above
if(p instanceof Crop)
{
p.setMaturity(2);
}
E:\test classes\ProduceTester.java:31: cannot find symbol
symbol : method setMaturity(int)
location: class Produce
p.setMaturity(2);
My question repeated:
How can I access methods defined in a child class when the object is of the parent class?