3

I am a bit confused about how to use constructor and setter in Java, please see the sample code below:

public class Name {
   private String name;

   public void setName(String name){
      this.name=name;
   }  
   public String getName(){
      return name;
   }
}

public static void main(String[] args) {
    Name a=new Name();
    a.setName("123");       
    System.out.println(a.getName());
}

It prints out 123, it is using setter method without constructor, I also wrote the other code below:

public class Name {
   private String name;


   public Name(String nm){
      name=nm;
   }
   public String getName(){
      return name;
   }  
}



public static void main(String[] args) {
   Name a=new Name("123");

   System.out.println(a.getName());

}

This one prints out 123 as well, it is using constructor without setter method, this is why I do not understand what the difference in using between constructor and setter, please advise, cheers!

AndyPerfect
  • 1,180
  • 1
  • 10
  • 25
pei wang
  • 295
  • 2
  • 8
  • 17
  • 1
    See the Java tutorial: http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html –  Oct 03 '13 at 15:51
  • In the second sample no one can change the name after it is constructed (immutable object); not the same as the first, where you can change the name to an existing object all times you want (mutable object). – Iván Pérez Oct 03 '13 at 15:53

7 Answers7

7

What if you want to change the value of name for an instance. Of course, you wouldn't use constructor for that, as it will create a new instance. You would use a setter in that case.

Of course, if you are writing an immutable class, then you wouldn't give any setters. Any modification in the instance fields, will create a new instance.

One more important point to understand here is, since you have provided a parameterized constructor in your 2nd code, the compiler wouldn't add any default constructor. So, the 2nd class doesn't actually have any 0-arg constructor. If you want to use it later on, then you have to add one explicitly.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

If you have a setter you can change the value anytime after creation. Otherwise, the field cannot be modified after construction (it's immutable).

Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
  • 1
    Hi Gabriel,based on your comment, I cannot change the value in the second sample as I was using constructor to create the value, but how about I change the value like this: Name a=new Name("123")--> Name a=new Name("456"); – pei wang Oct 03 '13 at 15:58
  • 1
    @peiwang You're not changing the value, but you are creating a new instance all together. – Rohit Jain Oct 03 '13 at 16:00
  • You didn't change the `name` field this way, but you created a new `Name` object and assigned it to `a`. – Gabriel Negut Oct 03 '13 at 16:00
3

It all has to do with the necessity of the name variable. If you put it as a setter, a new Name object can be created without setting the name variable. If it's in the constructor, you can't create a new Name object without specifying the name attribute.

Savv
  • 433
  • 2
  • 7
2

You can do both. It is a choice you must make depending on your design.

When you design a class, you must ensure that its instances are always in a consistent state.

In this case, a class Name without name might be considered as inconsistent. Hence, your class is in an inconsistent state until you call the setter. In this case, prefer the constructor option.

You can also decide to do both (constructor + setters) if you want to allow renaming.

To go further : All boxing classes in Java (Integer, Double, Float etc) are immutable. Hence, they have no setters on their embedded value.

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
2

The easiest way to understand it is just by looking at the words used to describe two methods:

Setter - Can be used to set name, so you can change the value of name at any other instance.

Constructor - I used to construct name, so it would construct a new name and therefor you could not use it to change the pre-existing one.

Dinocv
  • 367
  • 2
  • 3
  • 10
1

Constructors create a new instance of an object and you can instantiate that object with variables you want it to take on initially.

Setters let you change the values of variables after you create the object.

Getters let you access the values of the variables without actually letting you have access to them.

jackjack
  • 33
  • 7
0

In your question, after the first code snippet, you mentioned:

It prints out 123, it is using setter method without constructor

I need to make a small clarification about this. It's not actually right to say there's no constructor here. What you've got here is the default constructor. A default constructor is there unless you explicitly define a constructor, either parametrized or non-parametrized. A default constructor is the one constructor that the compiler automatically generates if the programmer doesn't explicitly define a constructor. A default constructor is also generally called a nullary constructor, since it holds nothing as argument.

Now coming to the point. Inside your 1st code:

private String name; 

This is your instance variable of access modifier private and type String and it's holding the value null. Why? Because, the default constructor assigns null to your instance variable. That's why it's called a nullary constructor.

When you're using a setter method, a certain value is assigned to your instance variable.

In this case:

public void setName(String name){
      this.name=name;
   } 

The public setter method contains the value 123 in its argument, since you provided this value in your main method, after creating an object of your Name class. Like this:

a.setName("123");

This value is now stored in your instance variable.

Ok, inside your 2nd code:

public Name(String nm){
      name=nm;
   }

What you've created here is a user-defined, parametrized constructor. Whenever there's a user-defined constructor, the default constructor is no longer created. The user-defined constructor is used to assign your instance variable a 'not-null' value. In this case, your constructor has the value 123 in its argument, so 123 will be assigned to your instance variable name

Since in your main method, during object creation:

Name a=new Name("123");

You provided the value 123 inside those brackets. This indicates you're creating a parametrized constructor which will take String-type argument of 123, which will eventually be assigned to your instance variable.

For a better understanding of these concepts about getters-setters and constructors, please refer to the following links:

Link-1

Link-2

Link-3

Community
  • 1
  • 1