Search code examples
javainstance-variables

How to inherit specific instance variables in java


I want to inherit specific instances from a superclass, not all of them.

For example:

public class Snake extends Reptile {
    private boolean hasLegs  = false;

    public Snake(double[] legLength, double tailLength, String color, boolean hasScales, boolean hasLegs) {
        super(legLength, tailLength, color, hasScales);
        this.hasLegs = hasLegs;
    }

I want to inherit all instance variables from the class Reptile except double[] legLength(as snakes doesn't have legs).

How can I do that without changing code in the Reptile class?

Thanks.


Solution

  • I think you are asking how to not have to pass all the parameters you don't need to the parent class. You can't do that, you need to pass them all, but that doesn't mean you have to expose them all in the child class:

    public Snake(double tailLength, String color, boolean hasScales) {
        super(null, tailLength, color, hasScales);
        this.hasLegs = false;
    }
    

    You can't just get some variables from the parent - you get them all. You can set them to values that make sense for your subclass. That is the whole point!