【问题标题】:How to inherit specific instance variables in java如何在java中继承特定的实例变量
【发布时间】:2020-05-18 17:29:42
【问题描述】:

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

例如:

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

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

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

谢谢。

【问题讨论】:

    标签: java instance-variables


    【解决方案1】:

    我认为您在问如何不必将不需要的所有参数传递给父类。你不能这样做,你需要将它们全部传递,但这并不意味着你必须在子类中将它们全部公开:

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

    您不能只从父级获取一些变量 - 您可以全部获取。您可以将它们设置为对您的子类有意义的值。这就是重点!

    【讨论】:

      猜你喜欢
      • 2013-11-10
      • 2012-11-05
      • 1970-01-01
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2012-12-03
      • 1970-01-01
      相关资源
      最近更新 更多