简体   繁体   中英

How can a class reference a variable from its containing composite class's parent class (which extends Activity)?

How can I get the value of "somevariable" from the "OtherClass"? Can/Should I use the Activity's context for this as I was trying below?

public class ParentActivity extends Activity {
  //This variable is reused by multiple Activities inheriting form this class
  protected static String somevariable = "text";   
  ...
}

public class MyActivity extends ParentActivity {
  @Override
  public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  myObject = new OtherClass(this);
  myObject.doSomething();
  ...
  }

...
}

public class OtherClass(){
  private Context c;
  private String b;

  OtherClass(Context context) {
    c = context;
  }

    doSomething() {
        // This does NOT work. 
        // How can I get somevariable from the ParentActivity????
        b = c.somevariable;   
    }
}

If you want to access the specific somevariable defined in class ParentActivity then you should try to access it as ParentActivity.somevariable since it is declared static :

public class OtherClass { // Why were there extra parentheses ()
  private Context c;
  private String b;

  OtherClass(Context context) {
    c = context;
  }

  doSomething(){
  b = ParentActivity.somevariable; // Try this at home ;)
  }

}

You could pass in the variable like so:

public void doSomething(String someVariable){
  b = someVariable;   
}
a = ParentActivity.somevarible;

应该工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM