Tim Carew Tim Carew - 17 days ago 4x
Java Question

How to access methods in subclasses from main method? (Java)

I am learning about superclasses and subclasses.
I have to create a superclass (Campsite) and then
two subclasses(FrontCountry and BackCountry), one of which has two additional subclasses(Serviced and Unserviced).
Not bad so far, I can do all of that.
But i'm asked this question at the very end.

*In CampTester, write another static Java method called statistics which takes, as its parameter, an array of Campsite objects and determines and outputs the following:
the attribute values for each object

the total number of Front Country sites in Terra Nova National Park, Newfoundland and Labrador

the total number of serviced sites (with 30 amp service) in Newman Sound, Terra Nova National Park, Newfoundland and Labrador

the locations of all Back Country sites in Gros Morne National Park, Newfoundland and Labrador

a list, by site number, of all the unserviced sites in Malady Head, Terra Nova National Park, Newfoundland and Labrador

I'm trying to use an enhanced for loop to print the attributes for each object in an array that i've created. simple enough. The problem lies within the fact that I cannot access the methods that can retrieve the information from the subclasses that I need to tally and present.(methods like getLocation, getAmpService, get Province)


Is it possible to access methods defined in a subclass from outside of that subclass (higher in the hierarchy)?


Not sure I understand your issue correctly, it seems you didn't do the casting when you access the methods in subclass.

Assume that getLocation, getAmpService methods are only existing in FrontCountry, but not in superclass Campsite. Before you want to access these methods, you need to cast the object into FrontCountry.

if (campsite instanceof FrontCountry) {
     FrontCountry frontCountry = (FrontCountry)campsite;