File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling a method of an object from another object

 
Hans Hovan
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(Hopefully my terminology is correct)

I am calling a method of an object from another object.

So for example I have this in main()


The encounter class has this:


The player character class has this:


So, to my understanding in main I am creating an Encounter object, then calling the Encounter object that is calling the PlayerCharacter object within it to do something (get a name in this case).

This seems to work when I've tested it.

My question is if there is a way to call a method of an object from another object that is a different class from where the object originally came. That was a mouth full..
In other words, if I have another class:


If I make an Encounter object in the Shop class though, a new PlayerCharacter object will be created within the Encounter object, but that PlayerCharacter object is a new one so I won't be able to alter the instance variables of original PlayerCharacter object...which is what I want to do. Of course I can have the methods of 'Shop' in the Encounter class and that will work. But for the sake of breaking up code into more readable/manageable chunks is there any way to do this?

Hopefully that question makes sense.
 
Winston Gutkowski
Bartender
Pie
Posts: 9472
50
Eclipse IDE Hibernate Ubuntu
  • 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hans Hovan wrote:If I make an Encounter object in the Shop class though, a new PlayerCharacter object will be created within the Encounter object, but that PlayerCharacter object is a new one so I won't be able to alter the instance variables of original PlayerCharacter object...which is what I want to do. Of course I can have the methods of 'Shop' in the Encounter class and that will work. But for the sake of breaking up code into more readable/manageable chunks is there any way to do this?

Hopefully that question makes sense.

Sort of...I think .

What about:That way, you can't set up a Shop without supplying it with an Encounter instance. Then your main() code might look something like:
PS: What you're proposing is not very safe.
  • For one thing: you shouldn't give clients direct access to your fields.
  • Secondly: You certainly shouldn't allow clients to update your fields directly. It's a recipe for disaster.

  • HIH

    Winston
     
    Don't get me started about those stupid light bulbs.
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic