【问题标题】:Default values in constructors of a subclass, to pass onto a superclass?子类的构造函数中的默认值传递给超类?
【发布时间】:2014-05-09 09:49:18
【问题描述】:

我有一个带有构造函数的类形状,在其构造函数中采用 (int Sides, Coodinates c, Color co),在类正方形中我不想在构造函数中有“int Sides”,我该怎么做这个?

//Shape
public Shape(int sides, Coordinates c, Color co) {
    this.sides = sides;
    this.c = c;
    this.co = co;
}

//Square
//Like this is gives me an error saying I need to include sides into my
//constructor. I don't want to request the number of sides when creating
//a square, it will always be 4, how do I do this?
public Square(Coordinates c, Color co, int w, int l) {
    //blah blah
}

假设我必须使用 super(4, c, co) 传递值 4 是否正确?

【问题讨论】:

    标签: java class object constructor superclass


    【解决方案1】:
    public Square(Coordinates c, Color co, int w, int l) {
        super(4, c, co);
        this.w = w;
        this.l = l;
    }
    

    是的,你是对的。但是,您还需要分配 wl 的值。

    【讨论】:

    • 是的,我只是没有输入,哈哈。感谢您为我解决这个问题:)
    猜你喜欢
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多