Quick question i imagine, but i’m having trouble getting a clear answer from googling.
So i have 3 objects. Card, Deck, Player.
Both Deck and Player have an array of cards and both are declared in main.
Can i do the following in main() to get a reference to a card from deck into player?
player.getcard(deck.draw())
deck.draw() returns a Card and getcard is: player.getcard(Card card)
And yes, I’m coming from c++.
Short answer: yes, assuming that
getcardactually puts its parameter into some private field in thePlayerclass.Long(er) answer: In Java, there are only two things available to you – primitives and references. The primitives are the numeric types, characters, and booleans. Everything else is an object, and all objects are references. So, when you write
a new object of type
Foois created and on the (garbage-collected) heap, and a reference, which you can also think of as a “pointer,” is placed on the stack. The Java language gives you few real ways to examine that reference, though (you can’t cast it to a pointer or along, for example) so you can just think of it as an opaque handle.So, when you write
the call
returns a reference to an object of type
Card, and that object is passed to theplayer.getcardmethod. Then, if thePlayerclass looks something likethen later calls to methods in
Playerthat access thecardsprivate field will see that the return value ofdeck.draw()has been added tocards.