Why do we need set method in most of Ja开发者_Go百科va classes when we implicitly initialize data members using a constructor.
public class Foo
{
private int id;
private String name;
public Foo(int id, String name)
{
this.id=id;
this.name=name;
}
public void setId(int a)
{
id=a;
}
public int getId()
{
return id;
}
}
and, say I have an application that instantiates Foo like this:
Foo obj1 = new Foo(2, "Example1");
Why would I require setId
in Foo
class when I have already initialize it during call of constructor? Thank you for your patience and time.
So you can change the value after initialisation.
It allows for the value to be changed from outside the class. Removing the setter would make the field immutable.
If you don't need to change the value after initialization, you don't need to. In fact it may be even better not to implement the setter method if the value is not going to be changed.
You might want to sell the class to others, who might like to set the value.
Or, you might like to implement some changes in the future, so you would code a set() method now so you don't have to worry about it then.
Or even, the code may have been generated by some sort of automatic code-generation tool which by default includes setters.
To answer the question in the title though, it's not required. You could take it out and the code would compile just fine.
精彩评论