I am very new to Java
and I am trying to understand some concepts. I have been reading a couple of books but I keep getting stumped around the same place. Look at the following code:
package Grade;
import static java.lang.System.out;
import java.util.*;
public class GradeBook {
private String courseName;
public void setCourseName (String name) {
courseName = name;
}
public String getCourseName() {
return courseName;
}
public void Display() // needs a string to run
{
out.println("Welcome to:" + getCourseName() );
}
}
I'm not sure why setCourseName()
needs ( String name ) to be there or where it even gets that value from. If someone could try to explain this in layman terms it will be greatly appreciated.
I originally posted a comment. But I decided to post an answer because I believe many are misreading this question.
It looks like you are actually asking about
parameters
and what they are used for, not about getters, setters, and encapsulation.I did a few searches and came across this link: http://www.homeandlearn.co.uk/java/java_method_parameters.html
That's a beginner's guide to Java specifically explaining what parameters are in Java.
The
methods
you write in Java will sometimes need values to complete their tasks. It is likely that you won't want your method to own these variables or inherit these variables, many times you will just want to give a method a variable so it can temporarily use it for a quick task or process then return a value. That is theString name
you see in the method definition, it is a parameter, a variable that is passed into the method. You can have as many variables as you like passed into a method. The variables will be assigned in order of the way you defined the method.For example, if you define:
And then you call that method like this:
Then inside myMethod, you will now be able to use the variables
one
,two
, andthree
to access those String values.An example of why you would want to pass in a value instead of having the method have access to it via the class is the java
Math
class. When you callMath.floor(decimalValue)
you want to give the Math class your decimalValue and have the Math class use it to determine the floor then return it to you. You don't want to write your program so that both the Math class and everything else have access to yourdecimalValue
all the time.Does this explain it all?