-1

the output is

   foo
   foo

but I was expecting it to be

    foo 
    bar
    foo

I do not under stand why the inner class does not work

class Test {

    private String foo = "foo";

    public void method() {
        System.out.println(foo);
        new Object() {
            public void bar() {
                foo = "barr"; 
                System.out.println(foo); //not work

            }
        };

        System.out.println(foo);
    }

}


    public class Main {
        public static void main(String[] args){
        Test t=new Test();
        t.method();
      }
   }
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Ahmed
  • 3
  • 1

3 Answers3

0

The output is actually:

foo

barr

barr

If you correctly invoke the bar() function after creating the anonymous class:

class Test {

    private String foo = "foo";

    public void method() {
        System.out.println(foo);
        new Object() {
            public void bar() {
                foo = "barr";
                System.out.println(foo); 
            }
        }.bar();  // Added invocation here

        System.out.println(foo);
    }

}

public class Main {

    public static void main(String[] args) {
        Test t = new Test();
        t.method();
    }
}
user681574
  • 553
  • 2
  • 15
0

There is no call to the method bar() of the anonymous Object class. That is why the print statement inside it is never executed. You can update the code as below :

new Object() {
            public void bar() {
                foo = "barr"; 
                System.out.println(foo); //not work

            }
        }.bar();

to call the bar method. Now that you have executed this method where you assigned the instance variable foo to value "barr" , the last print statement in the method() will print the updated value "barr".

Pallavi Sonal
  • 3,661
  • 1
  • 15
  • 19
0

It will affect the outer member but code which made change in member variable must execute so your code should be like this:

public class Main {

    private String foo = "foo";

    public void method() {
        System.out.println(foo);
        new Object() {
            public void bar() {
                foo = "bar";
                System.out.println(foo);

            }
        }.bar();

        System.out.println(foo);
    }

    public static void main(String[] args) {
        Main t = new Main();
        t.method();
    }
}

And output :

foo
bar
bar
Sunil Kanzar
  • 1,244
  • 1
  • 9
  • 21