如何在java中继承特定的实例变量

How to inherit specific instance variables in java

我想从超级class继承特定实例,而不是全部。

例如:

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;
    }

我想继承 class Reptile 的所有实例变量,除了 double[] legLength(因为蛇没有腿)。

如何在不更改 Reptile 中的代码的情况下做到这一点 class?

谢谢。

我想你问的是如何不必将不需要的所有参数传递给 parent class。你不能那样做,你需要全部传递,但这并不意味着你必须在 child class:

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

您不能只从 parent 中获取一些变量 - 您可以获取所有变量。您可以将它们设置为对您的 subclass 有意义的值。这就是重点!