I’m reading a book about java. It just got to explaining how you create a class called “deck” which contains an array of cards as its instance variable(s). Here is the code snippit:
class Deck {
Card[] cards;
public Deck (int n) {
cards = new Card[n];
}
}
why isn’t the this. command used?
for example why isn’t the code this:
class Deck {
Card[] cards;
public Deck (int n) {
this.cards = new Card[n];
}
}
this.is implicit.In general, it’s a best practice (at least I consider it one) to only use
thiswhen absolutely necessary. When you have a local variable namedcardsand a member variable namedcards, for example, you’ll needthis.cardsto refer to the member variable, ascardsrefers to the local variable.In such a case,
thisis a good idea (although it might be a better idea to rename the member variable).In every other case, where an implicit
thiscan work, use it.