• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using Variables From Another Object  RSS feed

 
Landon Blake
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This my be fairly simple, but I have to ask:
Can you use/reference a variable from another object within the current object? If you can, must the other object be public? Or is it just the variable that has to be public? Can you only do this with a static variable/static object combo?
For Example: I have a an object created from my "monster" class named Cyclops. Cyclops has an int variable named "strength". I have a monsterFerocity object with an int variable named "strengthMultiplier". Within the Cyclops object I want to call a method that increases the "strength" variable by the value of "strengthMultiplier". I'm not sure how to do this.

Thanks for any info,
Landon
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup, you can use public methods and variables on another object. You do it all the time with syntax like myArray.length - a variable - or String.size() - a method.
See if these ideas make sense. Not compiled, not tested, just thinking out loud ...

We made Ferocity a class. We give a Monster a Ferocity that is used to multiply its strength. We can change its Ferocity over time if it gets really angry or whatever.
Why put the multiply math inside Ferocity? I made it kind of a generic strength modifier. Right now it multiplies. Maybe another time it could add or raise to a power. I think we have to get into inheritance to make that interesting. Maybe another day.
A side note: I try to be real careful to start class names with a cap like Monster and variable names lower like myMultiplier. Java works if you turn those around, but readers of your code will be happier if it follows the conventions.
Hope that helped! Write back if not!
[ March 02, 2004: Message edited by: Stan James ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!