When to use Return and This in JAVA?

Asked

Viewed 201 times

0

I am learning POO in Java and sometimes when I am creating methods I feel a little lost in relation to what I should send to the main class. I wonder if there is any basic rule of when to use "Return" and when to use "This".

2 answers

2

Herbert, good night!

I’m also learning POO, I may be wrong, but come on. "Return" is always used when you are returning something to someone you have called a method. When you use "this", you are pointing to a variable.

You can, and will, use both together. This will happen a lot when using private type variables, where you will need public get and set methods to manipulate them.

A getNomeUsuario() method will have in the body a "Return this.nounUsuario;"

2


Well, 'Return' is when you use a method that is not of the void type, that is, it returns nothing. Example:

inserir a descrição da imagem aqui

That is, you will use Return to define what will be returned when that function is executed. In this case it will return an integer that is the result of multiplying the two numbers of the function/method.


Already 'this' you will use to make reference to the very context in which you are. Briefly, this will always be the class itself or the object already instantiated. With this you can modify the attributes of that object, you can manipulate the attributes of the already instantiated object. Example:

inserir a descrição da imagem aqui


It was clear?

  • 2

    You can also use Return in void type methods. Just declare return;. Obviously, no value is returned, but this way you interrupt the execution of the rest of the method.

  • That, I forgot to mention. Thank you for pointing out

  • 1

    Do not use code images, use the formatting available here in Sopt: select the code snippet you want and press the button {} at the top bar. Or, if you want keyboard shortcuts, the ctrl+k. The same effect is obtained by placing 4 spaces before the beginning of each line of code

  • Thanks for letting me know. I’m new and I didn’t know it.

Browser other questions tagged

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