DanielST
DanielST

Reputation: 14153

How are private objects passed in java?

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++.

Upvotes: 0

Views: 154

Answers (3)

Makoto
Makoto

Reputation: 106460

Strictly speaking, so long as getcard()'s return type is Card, then yes, you can do it. It would have to look like something below for it to be properly contained in the Player object. Note that this assumes that the getCard() method from the Deck class is declared as static, meaning that you don't have to create an instance of it to get the cards from it.

public class Player {

    private Card[] hand;

    public Player(int handSize) {
        hand = new Card[handSize];
    }


    ...

    public void getCard(int pos) {
        // Some logic to handle behavior with 0 cards, handSize cards, etc...
        hand[pos] = Deck.getCard();
    }
}

Upvotes: 1

Adam Mihalcin
Adam Mihalcin

Reputation: 14468

Short answer: yes, assuming that getcard actually puts its parameter into some private field in the Player class.

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

Foo f = new Foo();

a new object of type Foo is 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 a long, for example) so you can just think of it as an opaque handle.

So, when you write

player.getcard(deck.draw())

the call

deck.draw()

returns a reference to an object of type Card, and that object is passed to the player.getcard method. Then, if the Player class looks something like

public class Player {
    private List<Card> cards;
    // ...
    public void getcard(Card card) {
        cards.add(card);
    }
}

then later calls to methods in Player that access the cards private field will see that the return value of deck.draw() has been added to cards.

Upvotes: 1

eternaln00b
eternaln00b

Reputation: 1053

Yes, assuming that the "draw" method in the Deck class is visible (package private and in the same package as the class with the main method, OR a public method). Having said that, your methods could have better names:

player.drawCard(Card aCard)

would be nicer than "getcard" which makes it seem like you're getting a card FROM the player.

Upvotes: 1

Related Questions