• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cannot access function of extended class?  RSS feed

 
Oliver York
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a linked list of objects of a class I created called BaseballPlayer. I also have a Fielder and Pitcher class that extends BaseballPlayer. The linked list and list nodes accept elements of type BaseballPlayer. I put into the linked list both Fielder objects and Pitcher objects. The Pitcher class has a method that returns a float variable that is only found in the Pitcher class called EarnedRunAverage. However, in my main program it won't let me access the method. It says: The method getERavg() is undefined for the type BaseballPlayer. It does however, let me access methods in the super-class BaseballPlayer.
Here is main code and the Pitcher class code.



 
Ron McLeod
Bartender
Posts: 1603
232
Android Angular Framework Eclipse IDE Java Linux MySQL Database Redhat TypeScript
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't show it, but I assume that p.player is of type BaseballPlayer, not Pitcher, and BaseballPlayer does not have a method getERavg(). You could cast p.player to Pitcher to access the method:
     ((Pitcher)p.player).getERavg()
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
References to a superclass type cannot access any new methods defined in a subclass. This has to be the case because not all subclasses are guaranteed to have the same extra methods.
 
Oliver York
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ron McLeod wrote:You don't show it, but I assume that p.player is of type BaseballPlayer, not Pitcher, and BaseballPlayer does not have a method getERavg(). You could cast p.player to Pitcher to access the method:
     ((Pitcher)p.player).getERavg()


Worked! Thanks.
 
Ron McLeod
Bartender
Posts: 1603
232
Android Angular Framework Eclipse IDE Java Linux MySQL Database Redhat TypeScript
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great. Make sure you understand why you had a problem initially and why this type of solution helped.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Disagree. If you are having to add methods and cast things, you have problems with your design.
Can you get away with this sort of method in the Player class?Can you make the method abstract?

Avoid using floats. Use doubles instead.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!