I’m following a series of tutorials on multiple methods and instances. The author didn’t elaborate the details about some elements.
Why do you think would he put the method setName in a “public void” and then get the return using the “public String getName”. Why didn’t he just place the return randomName inside public void and in public void saying method declare the string g?
public class voidvoid {
private String randomName;
public void setName(String name){
randomName = name;
}
public String getName () {
return randomName;
}
public void saying () {
System.out.printf("you are %s", getName());
}
}
Using public void to set the value of a variable and public to get the value of a variable is the ‘correct’ way to do it. You can search “getters and setters in java” for more on the topic. Basically this provides public access to the stored name in terms of getting and setting the value of the variable. The method saying() is showing a use of the getter method, in this case, getName(). Note that the variable itself was declared private. This means that unless you extend this class, you have no access to the variable from outside this class except through the getter and setter. Say for example you do not like the name Fred. Inside your setName(String name) method you could say:
Any time someone tries to set the name “Fred”, it will be saved as “Jon Doe” instead. If they had direct access to the variable, they could just set the value to “Fred” any time.
This means you have ultimate control over what goes into the variable through your method.