Required class variables in Java?

Viewed 258

So say, for the purposes of illustration that I have an abstract class Animal, and every Animal has a numberOfLegs.
Dog extends Animal and all dogs have a numberOfLegs of 4.
Is it possible to make numberOfLegs...

  1. Static
  2. Required (everything that extends Animal has to define numberOfLegs, or there is some default value)
  3. Accessible from Animal (this one I'm not as concerned about, but if say the method walk() was called from Dog, could Animal view the number of legs without having to pass an extra value?)

Sorry if this is a strange question, and yes, I understand that I could do this easily in other ways, such as making it an instance variable instead of static, but I'm just kind of curious if there's a better way.

2 Answers

Neither static variables or instance variables participate in polymorphism. Just declare an abstract method, e.g. int getNumberOfLegs(), in the abstract class. Your Dog class could be:

class Dog extends Animal {
    private static final int NUMBER_OF_LEGS = 4;
    public int getNumberOfLegs () {
        return NUMBER_OF_LEGS;
    }
}

Is it possible to make numberOfLegs: Static

This would make every instance of a class that extends Animal have the same numberOfLegs. See: here for an explanation.

public abstract class Animal
{
    private static int NUMBER_OF_LEGS = 4;
}

Is it possible to make numberOfLegs: Required

Yes, you just have to make a property in the abstract class and initialise it in the constructor.

public abstract class Animal
{
    private int numberOfLegs;

    public int getNumberOfLegs()
    {
        return this.numberOfLegs;
    }

    public Animal(int numberOfLegs)
    {
        this.numberOfLegs = numberOfLegs;
    }
}

public class Zebra extends Animal
{
    public Animal(int numberOfLegs)
    {
        super(numberOfLegs);
    }
}

everything that extends Animal has to define numberOfLegs, or there is some default value

Furthermore, if you wanted a default value for number of legs, you could inlcude a constructor for Animal without a numberOfLegs parameter and set it to a value, say 4.

public abstract class Animal
{
    private int numberOfLegs;

    public Animal()
    {
        this.numberOfLegs = 4;
    }
}

Is it possible to make numberOfLegs: Accessible from Animal

Yes, you can call the method (if it's abstract in the Animal class) from any object that extends Animal

Zebra z = new Zebra(4);
System.out.println(z.getNumberOfLegs());
Related