javamethodsinstance-variablesmethod-parameters

Confusion over method parameter and instance variable having same name


    class Employee {
       public String name = "John";
       public void modifyName(String name)
       {
          name = name;     // I know using 'this' would be helpful, but I dont want to
       }
       System.out.println(name);
    }

     class Someclass {
         public static void main(String[] args)
         {
            Employee e1 = new Employee();
            System.out.println(e1.modifyName("Dave"));
            System.out.println(e1.name);  // Does this outputs John or Dave?
         }
     }

Does the method modifyName behave like a setter and change the instance variable name to be "Dave"?

Do methods only behave like a setter when they follow the naming convention setProperty?

modifyName is not working, will it work if it is named setName?


Solution

  • Within a method, a method parameter takes precedence over an instance variable. The method modifyName refers to method parameter name, not the instance variable name.