Variable scope access question  
Author Message
www





PostPosted: 2007-6-22 2:33:00 Top

java-programmer, Variable scope access question Hi,

I am not sure my question is valid or not. It is the following:


public class MyClass {

public void doA() {
int num = 10;

doB();
//Now, num value has been changed
}

public void doB() {
//I need to access and change the value num inside doA. But I don't
know how to do it.


}
}

Is this possible? Thank you for your help.
 
Steve W. Jackson





PostPosted: 2007-6-22 2:50:00 Top

java-programmer >> Variable scope access question In article <f5eg90$pkq$email***@***.com>, www <email***@***.com>
wrote:

> Hi,
>
> I am not sure my question is valid or not. It is the following:
>
>
> public class MyClass {
>
> public void doA() {
> int num = 10;
>
> doB();
> //Now, num value has been changed
> }
>
> public void doB() {
> //I need to access and change the value num inside doA. But I don't
> know how to do it.
>
>
> }
> }
>
> Is this possible? Thank you for your help.

In your example, the variable "num" is local to the method named "doA"
and is therefore not accessible to *any* code outside that method.
--
Steve W. Jackson
Montgomery, Alabama
 
Lew





PostPosted: 2007-6-22 9:05:00 Top

java-programmer >> Variable scope access question www wrote:
>> I am not sure my question is valid or not. It is the following:
>> public class MyClass {
>> public void doA() {
>> int num = 10;
>> doB();
>> //Now, num value has been changed
>> }
>> public void doB() {
>> //I need to access and change the value num inside doA. But I don't
>> //know how to do it.
>> }
>> }

Please do not embed TABs in Usenet posts.

Mark Rafn wrote:
> This isn't possible. It's also very much against the grain of structured
> programming - doB can not know that it's called only from within doA, so it
> can't access locals that only exist in doA.
>
> Find another way to design your class such that scope of data elements is
> cleaner.

As with so many programming problems, one can redefine the problem to achieve
the result.

Instead of an int, define a holder:

public class MyClass
{
static class Holder
{
public int num;
}
public void doA()
{
Holder h = new Holder();
h.num = 17;
doB( h );
}
public void doB( Holder hold )
{
hold.num *= 2;
}
}

Of course, within a single class this makes little sense. The usual approach
there is to use an instance variable. But for creating an OUT variable
between objects of different types the holder idiom works well.

--
Lew