How does the Setter method work in Java in this example :

47 Views Asked by At

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 **

1

There are 1 best solutions below

0
Marco Riccetti On

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:

public Person(String name,int age) {
    // name is the constructor argument
    // this.name is the class field
    this.name=name;
    this.age=age;
}

And then inside the setter:

public void setName(String name) {

    // this is not good in a setter
    name = this.name;

    // this is good
    this.name=name;

    // this statement says:
    // assign the name argument value 
    // to the class field identified by
    // the label name (this.name)

}

You can take a look at the following tutorial to learn the basics:

https://www.geeksforgeeks.org/getter-and-setter-in-java/