问题
I am unsure how to create a setter method in java.
Everything that I found on the internet either shows how to "generate" one in eclipse or doesn't include what I am looking for.
I am looking for a simple answer in plain terms, if that is possible.
I understand what a setter-method
does, but am unsure about the syntax and specific code.
Thank you for your time.
回答1:
A setter is a method which sets a value for one of your parameters. E.g. many people say it's not nice to have a public variable in a class:
public class SomeClass {
public int someInt = 0;
}
now you can access the variable someInt
directly:
SomeClass foo = new SomeClass();
foo.someInt = 13;
You should rather do something like that:
public class SomeClass {
private int someInt = 0;
// Getter
public int getSomeInt() {
return someInt;
}
// Setter
public void setSomeInt(int someIntNew) {
someInt = someIntNew;
}
}
and access it through:
SomeClass foo = new SomeClass();
foo.setSomeInt(13);
All this is just convention... You could name your setter-method however you want! But getters and setters are a good (and readable) way to define access to your class varaibles as you like it (if you want to make it read-only you could just write the getter, if you don't wan't anybody to read the value you could only write the setter, you could make them protected, etc...)
回答2:
I'm assuming you mean a setter method as in set an object?
private String yourString;
public void setYourString(String yourString) {
this.yourString = yourString;
}
This is basic code though so you probably mean something else?
Let me know.
回答3:
A small code for getter and setter
public class Test {
String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
Advantage of setter is that a setter can do sanity checks and throw IllegalArgumentException
.
来源:https://stackoverflow.com/questions/33806159/how-to-create-a-setter-in-java