Reputation: 19474
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?
Upvotes: 0
Views: 449
Reputation: 3454
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
}
}
Upvotes: 0
Reputation: 213331
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.
Upvotes: 0
Reputation: 198221
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.
Upvotes: 5