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