1

I have confusion about use of setter and constructor about value assigning. Why we use setter to set values independently if we can do it in a single constructor.

I have tried both methods using setter and construtor passing values and found no differnce. Need reasons for the differnece between them.

//setter 


public class NegaE {
String name;
int id;
public  void setname(String a){
    this.name=a;
}
public void setid(int  b){
    this.id=b;
}
public String getname(){
    return name;
}
public int getid(){
    return id;
}




// now through constructor



 public class NegaE {
    String name;
    int id;
   public NegaE(String a,int b){
       this.id=b;
       this.name=a;
   }
    public String getname(){
        return name;
    }
    public int getid(){
        return id;
    }

2 Answers2

3

You only call a constructor once. If you set the values in the constructor, and don't have setters, a user can never change the initial value unless some other object method with private access does it.

Objects that have private final data members that are initialized in the constructor and no setters are called "immutable" == "unchanging".

This can be a very good thing. Immutable objects are thread safe; you can share them between threads without concern. It's a more functional style of programming.

If you have setters you can update the state directly as you wish. These are mutable objects. You have to be careful sharing these across threads. Mutable, shared data is not thread safe.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 1
    Not true. You can't change it directly, but if you call another method on that object it can update the state according to its implementation. You talk like not having direct write access to the state is a bad thing. There are times when it's a very good thing, indeed. Some people would say that this functional style is better than object-oriented. – duffymo May 21 '19 at 17:39
0

A constructor sets the initial values, but those values will need to have the ability the change over time because things change.

Setters and getters allow you to make rules and modify the data if needed. Here's a real basic example to get the idea.

public String setName(String name){
  if(name == null){
      throw new InvalidNameException();
  }
  this.name = name;
}


public String getName(){
    if(this.name == null){
        return "No Name here";
    }
    return this.name;
}
RobOhRob
  • 585
  • 7
  • 17