传递给超类的子类构造函数中的默认值?

时间:2014-03-29 23:14:11

标签: java class object constructor superclass

我有一个带有构造函数的类形状,它在构造函数中采用(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?

1 个答案:

答案 0 :(得分:2)

public Square(Coordinates c, Color co, int w, int l) {
    super(4, c, co);
    this.w = w;
    this.l = l;
}

是的,你是对的。但是,您还需要指定wl的值。