Variable scope access question

W

www

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.
 
S

Steve W. Jackson

www <[email protected]> said:
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.
 
M

Mark Rafn

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.
}
}

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.
 
L

Lew

Please do not embed TABs in Usenet posts.

Mark said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top