简体   繁体   中英

Trying to access subclass methods

So i have an array called roster filled with both Pitchers and Batters and Players( the Player is the super-class of both pitchers and batters)

private Player[] roster;

roster[i] = new Pitcher();

How i would i access methods in the pitcher? For example:

 public double calculateTeamERA() { double ERA = 0; for(int i = 0; i < 25; i++) { if(roster[i] instanceof Pitcher) { ERA+= roster[i].calculateERA(); } } return ERA; } 

So i have a calculate method, and the method calculateERA() is correct syntax, i'm just wondering if there is a way to tell it to access the Pitcher object, because it gives me a syntax error there is no calculateERA() in the PLAYER method which there isn't it's in the pitcher method.

Actually found the answer! You have to type cast it and you have to obey the hierarchy so in my case it would be:

ERA+= ((Pitcher)roster[i]).calculateERA();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM