can subclass initialize superclass variable

i have an activity say A that is extended by many other activities , i have a variable in activity A which is used by all other sub activities(classes) extending it. I want to know if i can set a value for that variable from a sub-activity such that the change will reflect in all the other subclasses extending Activity A. i know its a basic question ,i am new to this any help is appreciated.

eg:
Activity A has
public String global = "ABC"

Activity B extent A
display(global); ---> ABC

Activity C extent A
display(global); ---> ABC

Activity D extent A
display(global); ---> ABC  

now how can i change global in Activity D such that Activity B and C should also be affected.

Answer

Seems like you want a variable whos value persists and remains same throughout.

But since you only want to your inherited classes to be able to update or read the variable, you can do something like this:

class A
{
  private static int your_var = 0;

  public int get()
  {
     return your_var;
  }
  public void set(int a)
  {
      your_var = a;
  }
}

 class B extends A
  {

  }

  class C extends A
  {

  }

In your static void main:

  new B().set(101);

  new C().get()  // this will return value 101.

Note: Here only one copy of variable your_var is created. And since it is private, only the non static getter setter methods will be able to read or modify it. Thus making it accessible only by either the containing class itself or the child class objects.

Leave a Reply

Your email address will not be published. Required fields are marked *