1 Reply Latest reply: Nov 23, 2010 1:26 AM by 796440 RSS

    Question related to local and instnace variabla

    796244
      class X
      {
      String name="sanjay";
                public String getName()
                {
                     return name;
                }
                          public void setName(String name)
                          {
                          name = name;
                          }
      public static void main(String ar[])
      {
      X ob=new X();
      ob.setName("nitesh");
      System.out.println(ob.getName());
      }
      }


      Output is sanjay
      Question:- Why it's output is not nitesh
        • 1. Re: Question related to local and instnace variabla
          796440
          You seem to be under the impression that when you write
          name = name;
          the compiler is able to read your mind and know that for the left-hand "name" you mean the member variable, and for the right-hand name you mean the local variable. This is not the case. When you have a local variable called "name", then if you write just "name", it always means the local variable. If you want to refer to a member variable with the same name as a local, you have to qualify it with "this":
          this.name = name;