In the Setter Method "setName()", int the first line, name=this.name ; takes the value of the string "nidhi"
in the second line,
this.name=name; what actually happens i can't understand
person.setName("vinoth"); -> why the name is not being changed here and only "nidhi" is being taken into consideration.
JAVA CODE:
/*
- @author Sanganidhi S
*/ package com.testpractice;
class Person{
private String name;
private int age;
public Person(String name,int age) {
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
//name = this.name;
this.name=name;
}
public void setAge(int age) {
this.age = age;
}
public void DisplayDetails() {
System.out.println("Name : "+name);
System.out.println("Age : "+age);
}
} public class GetterSetter {
public static void main(String[] args) {
Person person = new Person("nidhi",21);
person.DisplayDetails();
person.setName("vinoth");
person.setName("riya");
person.DisplayDetails();
//System.out.println(person.getClass());
//System.out.println(person.hashCode());
}
}
- //name=this.name; commenting this line gives vinoth
but still i don't have the clear understanding of the second line
**I want to what happens in the second line **
First, it is a bad practice to reassign the formal parameter with the class field within a setter.
Anyway, it is normal that if you reassign the value of the parameter passed to the setter and then assign it to the class field that value will always be the one previously assigned to the class field, in your case this is done in the constructor.
Here you do the first assignment:
And then inside the setter:
You can take a look at the following tutorial to learn the basics:
https://www.geeksforgeeks.org/getter-and-setter-in-java/