BleachEnjoyer
BleachEnjoyer

Reputation: 21

Java difference between using getter() and getter(Object c)

public class Card { 
    private String cardRankString;
    private String cardColorString;
    private int copiesOfCard;
    
    public Card(String rank, String color, int copies) {
    cardRankString = rank;
    cardColorString = color;
    copiesOfCard = copies;
    }   
    public int getCopies(Card c) {
        return c.copiesOfCard;
    }
    
    public int getCopies() {
        return this.copiesOfCard;
    }
}

I'm trying to create a Card Class and I want to make a getter that returns the number of copies of the card. I wanted to know which one of these two should I use or if both of them are valid. Only the Card Class is going to use them at the moment but maybe I also use them in another Class I'm doing. I don't understand the difference between these two getters basically.

Upvotes: -1

Views: 48

Answers (1)

David
David

Reputation: 219047

The difference is that one method returns the copiesOfCard value from whatever Card instance you supply to it (ignoring whatever instance you called it on) while the other returns the copiesOfCard value for whatever Card instance you call it on.

For example:

Card someCard = new Card("one", "two", 3);
int result = someCard.getCopies();

The above code would return the value of copiesOfCard on someCard and store that value in result. Alternatively:

Card someCard = new Card("one", "two", 3);
Card anotherCard = new Card("four", "five", 6);
int result = someCard.getCopies(anotherCard);

The above code would return the value of copiesOfCard on anotherCard and store that value in result.


As for which one to use, I see no reason to even have the one which accepts a Card instance as an argument. Why ignore the instance on which it's being called? Why add extra steps/code for no reason? Basically, why do this:

int result = someCard.getCopies(anotherCard);

When you can do this:

int result = anotherCard.getCopies();

And get the exact same result. The version which accepts a Card parameter is just introducing unnecessary confusion for you and future readers.

You could call it on the same instance of course:

int result = someCard.getCopies(someCard);

But... Why? Having to specify the Card instance twice in the same operation doesn't seem to accomplish much.

The version which accepts a Card parameter could be made static, which would make it slightly less confusing to use. But for this particular case I still see no reason to have it at all.

Upvotes: 2

Related Questions