如何将一个构造函数的值设置为另一个构造函数的值?

sku*_*ula 5 java constructor class-constructors

我目前正在我的大学学习初级 Java 课程,并且仍在学习编程的基础知识。本周我们一直在学习构造函数,我被困在本周作业的后半部分,因此非常感谢任何帮助。

实验室第二部分(我被卡住的部分)的说明如下:

编写类 Truck 的完整代码,如下面的类图所示。确保不要在构造函数中使用重复的代码。例如,带有 2 个参数的构造函数应该调用带有 1 个参数的构造函数来设置圆柱体的值。

这些是它想让我做的构造函数。

  • Truck()
  • Truck(int cylinders)
  • Truck(int cylinders, String manufacturer)
  • Truck(int cylinders, String manufacturer, double load)
  • Truck(int cylinders, String manufacturer, double load, double tow)

关于如何做到这一点的任何解释/示例都会很棒

Vya*_*lav 0

只需阅读简单的 Oracle 手册:

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html更仔细地阅读 stackoverflow.com

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)