• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling a method on an object from another class?  RSS feed

 
W Wilson
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right. So here's the deal. I have a class for employees. This class has basic information for the employee but no real pay information. And 2 subclasses, one for employee's paid for hourly rates and one for those paid a yearly salary. Each subclass has their own pay() method, that calculates and returns their pay and extra fields relative to help them calculate that.

I'm just curious, if I do this and create an object for an hourly paid employee like so:



How can I utilize that classes public method of pay() to gather this instance (or hourly paid employee)'s pay? I've tried doing so via:



But I get



As my error. Any idea why?

I can post more code if ya need it.
 
Ashwin Rao
Ranch Hand
Posts: 89
C++ Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at this:


You've created an object of type "something" but the reference to that object is of type "Object" (the left hand side of the assignment).
Java looks at the reference type of an object to decide if you can call a method on an object.
So when you call a method on hourly1 the JVM looks at the "Object" class to see if it has that method.
If it does not then you will get an error.
In this case class "Object" has no method called pay() so hourly1.pay() will throw an error.
Hope I helped!
 
W Wilson
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ashwin Rao wrote:Look at this:


You've created an object of type "something" but the reference to that object is of type "Object" (the left hand side of the assignment).
Java looks at the reference type of an object to decide if you can call a method on an object.
So when you call a method on hourly1 the JVM looks at the "Object" class to see if it has that method.
If it does not then you will get an error.
In this case class "Object" has no method called pay() so hourly1.pay() will throw an error.
Hope I helped!


Literally just thought of this. I'm sitting here going "Duhhhhhh."
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!