0

How would you declare a static variable in Super and instantiate it in subclass

Example

class A
{
  static Queue<String> myArray;

  public void doStuff()
  {
     myArray.add(someMethod.getStuff());
  } 

}
class B extends A
{
  myArray = new LinkedList<String>();

}

class C extends A
{
  myArray = new LinkedList<String>();

}

Obviously this doesnt work. But how would you go about declaring a variable; then doing some common functionality with the variable in the super class; Then making sure each subclass gets it own static LinkedList?

3
  • Why would you want to do this? What problem would this solve? Commented Oct 19, 2012 at 18:10
  • I want to have common functionality of array manipulation and have each subclass have its own static array. Therefore there will be two static arrays in total Commented Oct 19, 2012 at 18:13
  • In fact your first method itself will not compile. You are using static arrayList in non-static method.. Commented Oct 19, 2012 at 18:15

3 Answers 3

5

You can't do stuff along these lines. The closest you can do is to have an abstract (non-static) method in the superclass and do some stuff with it.

But in general, you cannot force subclasses to do anything static, and you cannot access subclasses' static fields from a superclass like you're trying to do.

Sign up to request clarification or add additional context in comments.

Comments

0

Since, you have subclass-specific properties to manipulate, you can't do it in the superclass, and it is not logical to do it anyways. As was already mentioned, you can do something like this:

abstract class A {
      public abstract void doStuff();       
    }

class B extends A    {
  static List<String>myArray = new LinkedList<String>();

  public abstract void doStuff() {
      // do B stuff
  }

}

class C extends A  {
  static List<String>myArray = new LinkedList<String>();
  public abstract void doStuff() {
      // do C stuff
  }

}

Comments

0

Static variable is bound to a class rather than an instance. If you need a separate static variable for subclasses, you need to declare them in each of your subclasses.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.