This is similar to the question : Is there a way to access the variables of the calling class in a method? But I am not quite able to get the exact answer. What I am trying to do:

class A{
    m()
    {
        int a=8;
        new B.m1();

    }
}

class B{
    m1()
    {
         //Print the value of a of class A (i.e 8) here     
    }
}

Constraints: Nothing in class A should be changed.Changes to be made in class B only! (such as putting B.m1(this) in class A etc. )

3

There are 3 best solutions below

4
On BEST ANSWER

No, this is not possible. Especially since a is a local variable.

If a had been a field, there might have been a remote possibility to solve this using some reflection / stack trace hack.

0
On

Read about 'this' keyword. But here it's not possible because you are talking about a local variable whose scope is just the method m()

0
On

Given the scope of 'a', passing it as a parameter is the only way of accessing it.