ssice
ssice

Reputation: 3683

How can I force subclasses to redefine a constant in Java?

How can I have a generic abstract class, let's say Animal, and have it implement a constant (or a variable; it doesn't mind) which must be redefined by all subclasses?

Example:

abstract class Animal {
    private static int venerableAge;
}

And force Dog to be defined something like

class Dog extends Animal {
    private static int venerableAge = 10;
}

I don't want different subclasses to be able to read nor write each others' value. Just the one of themselves.

I.e., each class must have its own static "instance" of the variable. And no one will access the parent's.

Is that possible in Java?

Upvotes: 3

Views: 2715

Answers (1)

Chris Knight
Chris Knight

Reputation: 25074

The trick is to do this with getter methods rather than directly with fields:

abstract class Animal {
   abstract int getVenerableAge();
}

class Dog extends Animal {
   private static int venerableAge = 10;

   public int getVenerableAge() {
      return venerableAge;
   }
}

EDIT: How about letting the constructor do the contract binding:

abstract class Animal {
    public Animal(int venerableAge){
       //carry out sense checks here. i.e.:
       if (venerableAge < 0) { /* doSomething */ }
    }
}

class Dog extends Animal {
   private static int venerableAge;

   public Dog(int age) {
      super(age)
      venerableAge = age;
   }
}

Now Dog and Cat are both forced to be created with venerable ages, but (as implemented above) can't see each others value.

Upvotes: 9

Related Questions