Reputation: 4033
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.
Upvotes: 1
Views: 27001
Reputation: 10789
returnname
is getter method, and used to obtain value of private variable. Read more about java access modifiers. tellname
just printer method and shows to standard output girlfriend name.returnname
returns string object, that variable sav ed in memory and you can print it out with using System.out.println(class2Obj.returnname())
. But you have method that print it, why do you need to do this? just call class2Obj.tellname()
(This is bad approach, though)PS. Don't call portion of java code script :)
Upvotes: 1
Reputation: 8463
setname
has return type void
, which means it doesn't return anything at all. The behavior of this function is to store the name for later retrieval.
returnname
has return type String
, and is to be called when you want to retrieve what was stored earlier.
The pattern, poorly exemplified, being used here is the getter/setter. They have complementary, but very different (opposite) behavior.
You could return a value with your setter setname
- but that's (for a beginner anyway) an unnecessary complication - let's just not go there yet, ok? Keep your methods single-purposed and focused.
tellname
is a helper function to print name-related output to the console.
Regarding:
also, in class1 we executed class2obj.tellname why didn't we execute class2obj.returnname ?
You could.. just as tellname()
called returnname()
. Your code in class1 might then replace
class2obj.tellname();
with
System.out.printf("your first girlfriend was %s",
class2obj.returnname()
);
Finally, to re-iterate / emphasize as others have suggested - go find a new tutorial.
Upvotes: 1
Reputation: 692231
First of all, if the code you've given is really the code used in the tutorial, then choose another tutorial. It doesn't even respect the standard Java naming conventions.
Then, to answer your question. An object is a mix of state (fields) and behaviour (methods). Some methods modify the state of the object. Some methods let you access the state of the object. Some methods allow doing both. Some methods use the state of the object and other objects to do something useful.
The method void setName(String name)
doesn't return anything. If it had a javadoc comment, and if the class and method names were wisely chosen, this comment would say:
/**
* Sets the name of this GirlFriend object. Replaces the previous name of
* the girl friend with the new name given as argument
*/
public void setName(String newName) {
this.name = newName;
}
This method modifies the state of the object, and doesn't need to return anything. Its responsibility is to change the name, and nothing else. Returning the new name doesn't serve any purpose, since the caller already knows it: it passed it as argument.
Later on, you could be interested in knowing the name of the girl friend:
/**
* Returns the name of this GirlFriend object
*/
public String getName() {
return this.name;
}
This method doesn't need any argument: it allows asking the girl friend for her name, and the method returns the name as an answer.
I would go with a good book, or with the official Java tutorial to learn more.
Upvotes: 6
Reputation: 29385
First, those scripts are actual class sources, but that's understandable - beginners do get the terminology wrong a lot, no matter what the language is :)
The conventions shown by these sources are quite terrible and most likely contribute to your confusion, but the bottom line is that all variables have a scope. Scope in a nutshell means where the variable can be used and scope is seen as one of the most important things to take care of in good code to avoid weird side effects and bugs that are difficult or just plain impossible to fix.
In the class2
above, you actually are correct, the method call returnname()
isn't actually required in tellname()
, since the private String girlname
field is in class private scope; that is, all methods within the class can see that particular field directly.
You also ask
why isn't it posible to return the girlname in the setname method?
which actually is possible, but as I already mentioned, the code here is very unconventional to normal Java which is definitely causing some confusion; the getX/setX method naming convention is what is known as property pattern, it is a convention where a class that has a private field of type Foo
exposes two public scope methods to allow users of the class to modify that field. This convention is part of JavaBeans, which is quite a large topic to side step into right now so you may want to read about that on your own. A simple class showing this would look like this:
public class FooFieldBean {
private Foo field;
public Foo getFoo() {
return field;
}
public void setFoo() {
this.field = field;
}
}
As a small bonus, here's the two class sources cleaned up to match common Java conventions. Pay attention to capitalization, whitespace usage and indentation.
import java.util.Scanner;
public 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();
}
}
public class Class2 {
private String girlName;
public void setName(String name) {
girlName = name;
}
public String getName() {
return girlName;
}
public void tellName() {
System.out.printf("your first girlfriend was %s",getName());
}
}
Upvotes: 0
Reputation: 347332
Because girlname
is private
, it can not be accessed by any other objects, so unless you provide some way to read the value, you will never be able to get the value back
Is it essential? No, but it is good practice. This prevents other objects from changing girlname
without you knowing it. This is actually a very important concept in OOP.
It would be quite vesiable to return the girlname
from the setname
method, but what would be the point. You've already passed in the value, that suggests that you already have access to the variable?
tellName
does nothing more than more then displays some text, in fact, it uses the returnname
method.
There is no reason why you can't call returnname
, but unless you assign it to a variable, there's not much point
You might to have a read of Learnng the Java Language
Upvotes: 0
Reputation: 2039
A java function is a part of code you wrote in order to do some action. Sometimes in end of this action you want an answer, sometimes you just need something done. When you want an answer you write a function that return a certain object other wise you set that function to void. and you don't return anything.
When you call setName you're action is to set the object name, so you didn't need anything back. When you call returnName you do want an answer - what is the object name, so there you use the return statement.
Upvotes: 0
Reputation: 3113
returnname()
and setname()
are examples of getter and setter methods (respectively). these are also known as mutator methods.
The main reason these types of methods exist is to honour encapsulation. This tutorial is obviously a very simple example where this isn't necessary, but imagine you're building a system where you want to let the user find information in a database. If you don't use a setter method and instead let the user directly access a variable which becomes part of the query run by the database then they could insert all kind of nasty code and hack your database (this would be known as an SQL injection attack). You prevent this by hiding the variable from the user (in your example the variable is private
) and set the value through setter methods. This method can be more complex than your example and look at the input to remove any unwanted input. Of course, now that the variable is hidden we need a way for other objects to access the value, thus the getter method.
In summary, it leads to a more secure system and lets the developer control how a variable is accessed to prevent misuse. Even though you're working on a very simple example, it's a good practice to learn as it will be important in building secure systems later.
Upvotes: 0
Reputation: 6868
Read about OOP concepts and java basics first to understand this. I wil try to explain it in short here.
girlname
is declared as a private variable , meaning it cannot be accessed directly from outside class2
. Hence the 2 methods to set and return the girlname
variable are made , to access the value of the variable from outside the class.
Also you could use classobj2.returnname
, which will return the value of the girlname
variable in class 2 and display it. classobj2.tellname
is used here to simple print the value of the variable directly.
Upvotes: 0