Example
abstract class A
{
protected static Queue<String> q = new ArrayList<String>();
abstract void myAbstractMethod();
public doConcreteThings()
{
//busy code utilizing a 'q'
q.add("something");
myAbstractMethod();
//busy code
}
}
class B extends A
{
public void myAbstractMethdo()
{
//creates concrete implementation using 'q'
}
}
class C extends A
{
public void myAbstractMethdo()
{
//creates concrete implementation using 'q'
}
}
No, there will be one queue shared by all the classes. One way to do this would be to have a separate static queue in each sub-class and add another protected getQueue() method that returns this queue. That way each sub-class can have its own queue.
Note that getQueue() would be a non-static method but return a static variable reference. That lets you implement it in sub-classes, while its behavior is "effectively" like a static method (it does not require access to this).
abstract class A
{
protected abstract Queue<String> getQueue();
public abstract void myAbstractMethod();
public doConcreteThings()
{
//busy code utilizing a 'q'
getQueue().add("something");
myAbstractMethod();
//busy code
}
}
class B extends A
{
private static Queue<String> q = new ArrayList<String>();
protected Queue<String> getQueue() { return q; }
public void myAbstractMethod()
{
//creates concrete implementation using 'q'
}
}
class C extends A
{
private static Queue<String> q = new ArrayList<String>();
protected Queue<String> getQueue() { return q; }
public void myAbstractMethod()
{
//creates concrete implementation using 'q'
}
}
Will each extended class get its own static Queue?
how do I make sure that common functionality of a static variable is defined in the parent but each class gets its own static variable
However, you can access the static variables defined in Parent class in your Child class with the Parent Class name.
WorkAround: -
You can define getters & setters (non-static) for your queue in each of your subclasses, and also have different static queue for each of them. Now, everytime the method of a subclass is invoked (through polymorphism), it will return the static queue defined in that class only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With