I am a beginner and I was watching a tutorial on youtube where the tutor talked about various methods. He talked about returning values in java but I didn't understand a thing about it. I will first share the script and then share my thoughts and queries.
Here is the class1 script:
import java.util.Scanner;
class class1{
public static void main(String args[]){
System.out.println("This is class1.");
Scanner x = new Scanner(System.in);
System.out.print("Please enter the name of your first gf here:");
String name = x.nextLine();
class2 class2obj = new class2();
class2obj.setname(name);
class2obj.tellname();
}
}
As you can see it is having the main method and what it does is : it first asks for the name of your first girlfriend and then store it in the variable name
. Then it links the class2 script which I will share after this and executes the setname method in the class2.
The class2
script is:
class class2{
private String girlname;
public void setname(String name){
girlname = name;
}
public String returnname(){
return girlname;
}
public void tellname(){
System.out.printf("your first girlfriend was %s",returnname());
}
}
In class2
, I can see that the setname
method sets the value of the name
to a private variable girlname
but my question is that what is it returning? Why do we require the returnname
method? Is it absolutely essential for inter-method variables? Also, why isn't it posible to return the girlname
in the setname
method?
I don't know a thing about the return, so a video or an article would help a lot. Also, this is the reason if you find what I say above strange.
Also, please tell me what the returnname
method and the tellname
method is doing.
Also, in class1
we executed class2obj.tellname
why didn't we execute class2obj.returnname
?
I am really confused right now so please don't mind if I am acting silly.