English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Lets say I have three classes Alpha, Beta and Gamma. Alpha instances Beta as myBeta. Beta has a non-static public variable called accessMe. Now, I can access the variable from Alpha as myBeta.accessMe. I can also access it from Beta as accessMe (of course). My question is how do I access it from Gamma. If I try to access it as Beta.accessMe, the compiler complains that I am referencing a non-static variable from a static context (which is true since "Beta." makes it static). Since I havent instanced Beta in Gamma, I can't refer to it as myBeta.accessMe. I don't want to make betaString static. I don't want to pass myBeta as a parameter to Gamma, nor do I want to make Gamma an Inner Class. I just want to access accessMe, a public variable. Isn't there some easy obvious way to do this?

2006-11-05 14:22:34 · 2 answers · asked by heartsensei 4 in Computers & Internet Programming & Design

2 answers

The short answer is that your Gamma instance must have a reference to the Beta object for which you want the accessMe value , or the Alpha object must provide a way for Gamma to get a reference to it's Beta instance.

One way:
public class Alpha {

public Beta myBeta = new Beta (...);

}

and then you must pass a reference to the Alpha instance that owns the Beta instance to Gamma. Then the Gamma object can access the value as theAlpha.myBeta.accessMe.

The other way is for the Alpha class to provide a method (the better approach).

public class Alpha {

public Beta myBeta = new Beta (...);

public String getAccessMe(){
return myBeta.accessMe;
}

}

In any event, Gamma will need a way to get a reference to the Beta instance either directly, or via the Alpha instance.
}

2006-11-06 13:05:17 · answer #1 · answered by vincentgl 5 · 1 0

Er... I am pretty sure that it is impossible to refrence a non-static variable from a static context. *sigh* stupid picky java... you seem to know what you're doing in java... can you take a look at my question plz?
Thanks

2006-11-05 14:37:27 · answer #2 · answered by ichr123 2 · 0 0

fedest.com, questions and answers