-1

Please have a look at the code below :

public class SampleClass{
        String name;
        public SampleClass(){

        }
        public void setName(String s){
            name = s;
        }
        public String getName()
        {
            return name;
        }
        public static void main(String d[]){
            PojoClass p = new PojoClass();
            SampleClass s = new SampleClass();
            s.setName("jack");
            System.out.println(s.getName());
            p.setSample(s);
            System.out.println(p.getSample().getName());
            s.setName("Fgk");
            System.out.println(p.getSample().getName());
            p.recMod(s);
            System.out.println(p.getSample().getName());
            p.changeVal(s);
            System.out.println(p.getSample().getName());
        }
    }

    class PojoClass{
        SampleClass s;
        public void setSample(SampleClass d){
            s=d;
        }
        public SampleClass getSample()
        {
            return s;
        }
        public void recMod(SampleClass s){
            SampleClass g = new SampleClass();
            s=g;
            //g.setName("FGH");
            s.setName("hjk");
        }
        public void changeVal(SampleClass s){
            s.setName("hjkjkl;k;k");
        }

    }

I am trying to run this code but unable to get why we get the output as Fgk when we call recMod() method. Also if I uncomment g.setName("FGH") then also the output remains the same.

1 Answers1

2

You're assigning the name "hjk" to the SampleClass s object passed into recMod, which is shadowing the class member s. Change it to this.s = g; and you'll set the name of the class member instead.

splrs
  • 2,424
  • 2
  • 19
  • 29