Getters and setters in Java [closed]

2019-06-07 12:15发布

问题:

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.

回答1:

You need to use getter and setter methods for this class because the courseName field is private; code outside the class cannot access the field directly. Other code that uses the class (usually called client code) would supply the argument value passed to setCourseName and would use the value returned by getCourseName.

With this simple example, it's hard to appreciate why the class would be designed this way. One could just as easily make courseName a public field and let client code manipulate it directly. However, as the class becomes more complicated, using the get/set style offers many advantages. Here are some:

  • Using getter/setter methods helps insulate client code from changes to how the class is implemented. For instance, you might decide later that the course name has some sort of internal structure and you want to keep the pieces of the name in separate fields. You would be able to simply change how setCourseName and getCourseName are implemented and client code would not need to be updated.

  • Automated software generation tools rely on the existence of property getters and setters. With these tools, you can simply model your class as having a "courseName" property and it will generate code that uses the appropriate methods.

  • You might later decide that changing the course name should have certain side effects (such as updating a course catalog somewhere). Implementing these dependencies can be done by modifying the setCourseName method.

With object-oriented programming in general, the default design should be to hide the class implementation as much as possible and expose the class only through methods. There are sometimes good reasons to violate this principle, but adhering to it tends to result in more robust software.



回答2:

Gradebook's Story

GradeBook has a secret. It's the private member variable called courseName.

Gradebook: No one touches this variable but me!

Knock, knock. It's the Teacher class.

Teacher: Hey, I found out that you're a GradeBook class, let me assign you a course for today. I suppose you have a courseName variable?

Gradebook: No, I don't! (gulp)

Thinking...Hmmm, how can I keep little my secret but still let her give me that course name? I need that badly.

Gradebook: Okay, you almost got me there. I won't tell you if I have a courseName variable, that's too personal. But you can write down the course in the method setCourseName. Is that okay? I'll handle it from there. :)

Actually...

No one is forcing you to write the setCourseName. Your program will run just fine. You have the option to make courseName public.

public String courseName;

But and it's a big BUT: it's tantamount to putting your diary in the lawn and letting your neighbor, or any passerby, have their way with it. You wouldn't do that right?

Encapsulation, in layman's terms.



回答3:

Welcome to Object Oriented Programming. Your member variable courseName private and cannot be accessed from outside.

To provide read access to courseName variable you provide a getter method:

public String getCourseName() { ... }

And to provide write access to courseName your provide a setter method:

public void setCourseName (String name) { ... }

Here name is being passed as an argument to setter method which is being used to set value into private variable courseName



回答4:

This class itself never uses setCourseName but theoretically it could be used to change the private variable courseName.



回答5:

The reason is that you are unable to access the private attribute (courseName) from outside your class. The get and set methods are respectively designed to access (get) and change (set) its value.



回答6:

Please read about encapsulation and data abstraction . Somewhere in that program , someone is instantiating the GradeBook class and then setting its member variables . A sample would be :

package Grade;  
import static java.lang.System.out;
import java.util.*;

class GradeBook {

    private String courseName;

    public void setCourseName (String name) {
       courseName = name;

    }
    public String getCourseName() {
      return courseName;
    }

   public void display()
   {
      out.println("Welcome to:" + getCourseName() );  
   }
}

public class Main {
  public static void main(String[] s) {
   // creating instance of GradeBook class
   GradeBook gb = new GradeBook(); 
   // assigning value to the instance variable 'courseName' using setter 
   // as it a private member and cannot be accessed outside the class definition.
   gb.setCourseName("java");
   // calls a public method to display the value.
   gb.display();
}


回答7:

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 the String 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:

public void myMethod(String one, String two, String three) {
    some code;
}

And then you call that method like this:

myMethod("one", "two", "three");

Then inside myMethod, you will now be able to use the variables one, two, and three 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 call Math.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 your decimalValue all the time.

Does this explain it all?



标签: java get set