Question

public abstract class SuperClass {
    public int x, y;
    public static int z;
}

I want every subclass of SuperClass to have the static variable z. Naturally z will contain a different value for each subclass. I'm hoping to avoid defining z in every subclass, since it's going to be a functional dependancy of values x and y; Is this possible?

Was it helpful?

Solution

Unlike instance variables that are "one per instance", static variables are not "one per subclass" - they are "one per declaring class". In other words, subclasses of SuperClass share SuperClass.z, but they cannot "override" it on a class-by-class basis.

It does not mean that you cannot implement it yourself: on way to make your own per-subclass storage of integers is adding a static Map<Class,int> zs to SuperClass, with optional functions for accessing the data:

public abstract class SuperClass {
    public int x, y;
    private static Map<Class,Integer> zs = new HashMap<Class,Integer>();
    protected static int getZ(Class c) {
        Integer res = zs.get(c);
        return res == null ? -1 : res.intValue();
    }
    protected static void setZ(Class c, int v) {
        zs.put(c, v);
    }
}
class SubClassOne extends SuperClass {
    public int getZ() {
        return SuperClass.getZ(SubClassOne.class);
    }
}
class SubClassTwo extends SuperClass {
    public int getZ() {
        return SuperClass.getZ(SubClassTwo.class);
    }
}

OTHER TIPS

Probably the best way to do this is to have a z() method or similar in the abstract class, and override the method in the subclasses you want.

Example:

public abstract class SuperClass {
  public int x, y;

  protected int z() {
     return 42; // protected so only subclasses can see it - change if required
  }
}


public class SubClassOne extends SuperClass {

  public void foo() {
    // do something...
    int z = z();
    // something else...
  }
}

public class SubClassTwo extends SuperClass {

  @Override
  protected int z() {
    return 1;
  }

  // use z() accordingly
}

if i understand you correctly then do

public abstract class SuperClass {

  public int x, y, z;
  public SuperClass(int z) {

    this.z = z;

  }

}   

then any class that extends this class inherits z;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top