java - 子类构造函数中的默认值要传递给父类(super class)吗?

标签 java class object constructor superclass

我有一个类形状,其构造函数在其构造函数中采用 (int Sides, Coodinates c, Color co) ,在类 Square 中我不想在构造函数中包含“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 是否正确?

最佳答案

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

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

关于java - 子类构造函数中的默认值要传递给父类(super class)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738147/

相关文章:

java - 当方法名与类名相同时如何实例化嵌套类?

c++ - 将成员函数的返回类型引用到 C++ 中的自定义类

swift - 使用 Realm Swift 3.0.1 创建数据库

Javascript - 按对象数组中的数据分组

java - 没有 GeoJSON 文件的 Mapbox 聚类

java - 无法在面向对象编程、数组中为函数赋值

java - 我正在尝试使用 android studio 应用程序将 String 转换为数组然后转换为整数

java - eclipse -> 错误 : Could not find or load main class hello

javascript - 没有定义类的对象实例

java - 测试运行失败: Instrumentation run failed due to 'kotlin.UninitializedPropertyAccessException'