What good . this in java

Asked

Viewed 6,370 times

0

Hello, then, I’m starting in java and would like to better understand what is .this. I imagine it has something to do with the current class or something like that. But I’m not sure. I’ll post a part of my code that . this is contained

   class Conta {  
   int numero;
   String dono;
   double saldo;
   double limite; 
  // Os metodos que ultilizam o .this
   boolean saca(double valor) {
         if (this.saldo < valor) {
           return false;
         }
         else {
           this.saldo = this.saldo - valor;
           return true;
         }
   }
      void deposita(double quantidade) {
         this.saldo += quantidade;
   }
}

Has public class also that is only giving value to the variables created in the Account class

1 answer

2

This is to differentiate when the method has the same parameter name as the class, in its code this does not happen, then it has no need of this, if you had any attribute in the class with the value name, then that method would need a this.value, to say that you want to change only the attribute of that instance and not of the class

By the looks of studying by the Canons, soon you will understand this, these methods will grow well yet rsrs

but roughly eh that, if your method passes parameter with the same name of a class attribute, then to refer to that method instance, use this. otherwise java will understand that it wants to change the class attribute

Browser other questions tagged

You are not signed in. Login or sign up in order to post.