繁体   English   中英

如何在Java中从超级类继承子类的构造方法

[英]how to inherit Part of Constructor from super class to sub class in java

如何继承一些超类构造函数的参数到子类构造函数? 例如,我只想将体重和身高继承给子类,那么如何为子类构造承包商呢?

public abstract class People {

    protected double weight;

    protected int height;

    protected String mood;

    public People(double weight, int height, String mood) {

        this.weight = weight;
        this.mood = mood;
}

public class Health extends People {

    private String bloodType;

    public Health(double weight, int height, String bloodType){
        super(weight,height); // this won't work
        this.bloodType = bloodType;
}

要么你需要在超类(可能为常数)情绪向构造函数, 或者你需要一个构造函数添加到不采取心情超。 您需要问自己,每个Question/People是否真的需要一种情绪,以及DivisionQuestion/Health的情绪是什么。 (就其当前使用的类名而言,当前代码不一致是无济于事的。)

就像调用普通方法一样,您不能为某些参数提供参数,而不能为其他参数提供参数。

您只需要重载构造函数,或者可以在Super Class中为变量“ mood”使用默认值。 尽管如此, 有效的Java建议还是使用静态工厂方法而不是重载构造函数。

只是为了补充Jon Skeets和Harshil Sukhadias的答案。 您或者需要两个构造函数,一个只接受heightweight并为mood设置默认值,或者您使用默认值调用第一个构造函数。

public abstract class People {
    // ...
    public static final String MOOD_DEFAULT = "Happy";
    public People(double weight, int height, String mood) {
        // ...
    }
    // second ctor, calling the first with a default for mood...
    public People(double weight, int height) {
       this(weight,height,Question.MOOD_DEFAULT);
    }
}

public class Health extends People{
    // ...
    public Health(double weight, int height, String bloodType) {
        super(weight,height);
        // ... or super(weight,height,Question.MOOD_DEFAULT);
    }
}

具有这种类型的类层次结构,实现构建器模式可能很有用,有关更多详细信息,请参阅Josuah Blochs“ Effective Java”的第2章第2条。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM